Filter Array of Objects by Key: 5 PHP Code Examples (2023)
![filter array of objects by key in PHP](https://assets.fuelingphp.com/2021/09/Filter-by-key.png)
Filter Array of Objects PHP Code Example The following code snippet is a quick way to filter array of objects by key using the array_filter function. We recommend using the method for most array filtering use cases. Feel free to use this snippet and then follow along for more explanation. <?php // Dummy data just to populate function. // I'm creating a json string as its an efficient way to create an array of objects. // You can ignore this part and replace $objectsArray with your array. $content = '[{"type": "cat", "name": "charles"}, {"type": "dog", "name": "sam"}}, {"type": "donkey": "name": "frank"}]'; $objectsArray = json_decode($content); //Array_filter to filter objects with cat as type // This is where the work is done. $filtered_arr = array_filter( $objectsArray, function($key){ return $key === 0; }, ARRAY_FILTER_USE_KEY); //Gets the filtered array. print_r($filtered_arr); /* OUTPUT Array ( [0] => stdClass ( [name] => charles [type] => cat…