In PHP we either create objects and their array, or database returns array of objects as result-set of some query. There we might need to find an object which have a particular property-value pair. There is no direct function available in PHP to perform the same so I’m explaining here how can we find object by value in array of objects by using a foreach loop.
We have the following array of objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [0] => stdClass Object ( [ID] => 52 [name] => Pankaj ) [1] => stdClass Object ( [ID] => 96 [name] => David ) [2] => stdClass Object ( [ID] => 422 [name] => Maris ) [3] => stdClass Object ( [ID] => 10542 [name] => Vinod ) ... |
Here we wish to obtain object with ID = 422
. Let us do it.
Find object by value in array of objects with foreach loop
1 2 3 4 5 6 7 8 9 10 11 12 | $item = NULL; $val = 422; foreach($objAry as $obj) { if ($val == $obj->ID) { $item = $obj; break; } } $name = NULL; if(!is_null($item)) $name = $item->name; |
Rather easy! And if you don’t know if an object in array has particular property or not, you can modify the if condition inside foreach loop using isset
as follow:
if (isset($obj->ID) && $val == $obj->ID)
It’s the way to find an object with having a value in array of objects.