Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array intersect for object array php

Tags:

arrays

object

php

I want to know how to array_intersect for object array.

like image 785
zahir hussain Avatar asked May 14 '10 13:05

zahir hussain


People also ask

What is array intersect?

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}

How do I check if an array contains another array in PHP?

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.

What is intersection PHP?

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...)

How do I check if two arrays have the same element in PHP?

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.


2 Answers

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.

like image 58
Mateusz Nowak Avatar answered Sep 16 '22 14:09

Mateusz Nowak


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).

like image 37
D. E. Avatar answered Sep 19 '22 14:09

D. E.