Can the in_array
function compare objects?
For example, I have an array of objects and I want to add them distinctly to another array. Is it possible to check if an object has already been added like so:
in_array($distinct, $object);
or is there any other way?
PHP has a comparison operator == using which a simple comarison of two objecs variables can be performed. It returns true if both belong to same class and values of corresponding properties are are same.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
in_array will be faster for large numbers of items. "large" being very subjective based on a lot of factors related to the data and your computer.
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
You can use strict comparison:
in_array($object, $array, TRUE);
Usage example:
$a = new stdClass(); $a->x = 42; $b = new stdClass(); $b->y = 42; $c = new stdClass(); $c->x = 42; $array = array($a,$b); echo in_array($a, $array, true); // 1 echo in_array($b, $array, true); // 1 echo in_array($c, $array, true); //
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