I want to know how to array_intersect for object array.
The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order. For example. Input: A[] = {1,4,3,2,5, 8,9} , B[] = {6,3,2,7,5} Output: {3,2,5}
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.
PHP | array_intersect() FunctionThe function is used to compare the values of two or more arrays and returns the matches. The function prints only those elements of the first array that are present in all other arrays. Syntax: array array_intersect($array1, $array2, $array3, $array4...)
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.
You can use array_uintersect in conjunction with spl_object_hash, see an example:
array_uintersect($a, $b, function($a, $b) {
return strcmp(spl_object_hash($a), spl_object_hash($b));
});
where '$a' and '$b' are arrays of some objects that you want to intersect.
Just for completeness: Implement __toString()
method in your object returning a unique value. For database entities this might be as easy as returning the fully qualified class name postfixed with the ID of the record. But it can also be arbitrarily complex by doing some hashing or even worse things.
In my opinion, it's the class's duty to serialize itself or create something unique to compare its objects by. Using anything outside of a class to serialize an object might result in strange behaviour (including comparing objects of different classes, which must never result in equality).
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