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

I have an array containing several objects. Is it possible to check if any value exists in any of the objects, for example. id-> 27 without loop ? Similar to the PHP in_array () function. Thank.

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

No. If you often need a quick direct search for values, you need to use the array keys for them, which are quickly updated for the search. For instance:

// 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 search for objects with different keys, so you cannot index them by one specific key, you need to look for different search strategies, such as binary search .

+4
$results = array_filter($array, function($item){
   return ($item->id === 27);
});
if ($results)
{
   ..  You have matches
}
+3

You will need to do the loop anyway, but you don’t need to manually implement the loop yourself. Take a look at array_filterfunction . All you have to do is provide a function that checks objects, something like this:

function checkID($var)
{
    return $var->id == 27;
}

if(count(array_filter($input_array, "checkID")) {
    // you have at least one matching element
}

Or you can do it in one line:

if(count(array_filter($input_array, function($var) { return $var->id == 27; })) {
    // you have at least one matching element
}
+2
source

array_search - Searches for an array for the given value and returns the corresponding key, if successful

$key = array_search('your search', $array);
+1
source

You can do:

foreach ($array as $value)
{
   if ($value == "what you are looking for")
       break;
}
0
source

All Articles