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.
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.
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.
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 .
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With