Stu Stu - 1 month ago 6
PHP Question

Is it possible to check if a value exists inside an array full of objects without looping?

I Have an array holding multiple objects. Is it posible to check if a value exists in any one of the objects e.g. id->27 without looping? In a similar fashion to PHP's in_array() function. Thanks.

> array(10)[0]=>Object #673
["id"]=>25
["name"]=>spiderman
[1]=>Object #674
["id"]=>26
["name"]=>superman
[2]=>Object #675
["id"]=>27
["name"]=>superman
.......
.......
.........

Answer

No. If you often need quick direct lookup of values, you need to use array keys for them, which are lightning fast to lookup. For example:

// prepare once
$indexed = array();
foreach ($array as $object) {
    $indexed[$object->id] = $object;
}

// lookup often
if (isset($indexed[42])) {
    // object with id 42 exists...
}

If you need to lookup objects by different keys, so you can't really index them by one specific key, you need to look into different search strategies like binary searches.

Comments