Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does in_array check if an object is in an array of objects?

Does in_array() do object comparison where it checks that all attributes are the same? What if $obj1 === $obj2, will it just do pointer comparison instead?

I'm using an ORM, so I'd rather loop over the objects testing if $obj1->getId() is already in the array if it does object comparison. If not, in_array is much more concise.

like image 702
yellottyellott Avatar asked Jul 31 '12 15:07

yellottyellott


People also ask

How do you check if an object 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. Example: html.

How do you check if an object is in an array in PHP?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

How do you check if an object is in an array typescript?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.


1 Answers

in_array() does loose comparisons ($a == $b) unless you pass TRUE to the third argument, in which case it does strict comparisons ($a === $b).

Semantically, in_array($obj, $arr) is identical to this:

foreach ($arr as &$member) {
  if ($member == $obj) {
    return TRUE;
  }
}
return FALSE;

...and in_array($obj, $arr, TRUE) is identical to this:

foreach ($arr as &$member) {
  if ($member === $obj) {
    return TRUE;
  }
}
return FALSE;

...and to quote the manual on what this actually checks:

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

like image 87
DaveRandom Avatar answered Oct 07 '22 18:10

DaveRandom