PHP - find entry by object property from an array of objects

Alex picture Alex · Jan 20, 2011 · Viewed 267.4k times · Source

The array looks like:

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

And I have a integer variable called $v.

How could I select an array entry that has a object where the ID property has the $v value ?

Answer

Phil picture Phil · Jan 20, 2011

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

For the former, something like this

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes