Find object by value in array of objects

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:

Here we wish to obtain object with ID = 422. Let us do it.

Find object by value in array of objects with foreach loop

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. 

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.