'How do check Identical array between two arrays in PHP [closed]

I have two arrays as below:

$arr1 = array(1,2,3, 1,2,3, 1,2,3);
$arr2 = array(1,2,3)

I need to check that they are same array. I did something like:

$result = !empty(array_intersect($arr1, $arr2));
print $result; 

Result : is true

But it is wrong for my requirements.

Say for example if I update the arrays:

$arr1 = array(1,2,3, 1,2,3, 1,2,3, 7);
$arr2 = array(1,2,3)

Result : is still true . I need the result false

Question: How do I get the result that above arrays are not same after updating the array $arr1 in PHP?



Solution 1:[1]

As far as I understood, your $arr1 needs only the elements that are in $arr2. When $arr1 has any new element, you claim that it is not identical.

From this understanding, you need to use array_diff:

$arr1 = array(1, 2, 3, 1, 2, 3, 1, 2, 3, 7);
$arr2 = array(1, 2, 3);

if (count(array_diff($arr1, $arr2))) {
    echo 'Not Identical';
} else {
    echo 'Identical';
}

You can use empty instead of count. In that case, just switch the conditions.


Explanation :

array_diff gives you the difference of elements that are not present in any of the arrays. So in this case it holds:

Array
(
    [9] => 7
)

array_intersect gives you the intersection of elements that are present in both arrays. So in that case it holds:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 1
    [4] => 2
    [5] => 3
    [6] => 1
    [7] => 2
    [8] => 3
)

So, this is the reason why your empty function returns true when you use array_intersect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1