Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

oop

php

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 
           ....... 
           .......
           .........
like image 265
Stu Avatar asked Sep 05 '12 09:09

Stu


People also ask

How do you check if a value exists in an array of objects?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.

How do you check if a value exists in an array of objects TypeScript?

Use the includes() method to check if an array contains a value in TypeScript, e.g. if (arr. includes('two')) {} . The includes method will return true if the value is contained in the array and false otherwise.

What function will test if a value is in an array?

The Array.isArray() static method determines whether the passed value is an Array .

How do you check if an array of objects contains a value in react?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.


2 Answers

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.

like image 102
deceze Avatar answered Nov 02 '22 23:11

deceze


$results = array_filter($array, function($item){
   return ($item->id === 27);
});
if ($results)
{
   ..  You have matches
}
like image 43
Lee Davis Avatar answered Nov 03 '22 00:11

Lee Davis