PHP - Check if two arrays are equal

You can use the array_diff() function to check if two arrays are equal. The array_diff() function compares two arrays and returns an array of the values in the first array that are not present in the second array. If the returned array is empty, it means that the two arrays are equal.

Here's an example of how you can use array_diff() to check if two arrays are equal:

<?php

$array1 = [1, 2, 3, 4];
$array2 = [1, 2, 3, 4];

if (array_diff($array1, $array2) == []) {
    echo "The arrays are equal.";
} else {
    echo "The arrays are not equal.";
}

Watch a course Learn object oriented PHP

Alternatively, you can use the array_intersect() function to check if two arrays are equal. The array_intersect() function compares two arrays and returns an array of the values that are present in both arrays. If the returned array is identical to one of the arrays, it means that the two arrays are equal.

Here's an example of how you can use array_intersect() to check if two arrays are equal:

<?php

$array1 = [1, 2, 3, 4];
$array2 = [1, 2, 3, 4];

if (array_intersect($array1, $array2) == $array1) {
    echo "The arrays are equal.";
} else {
    echo "The arrays are not equal.";
}

You can also use the operator to check if two arrays are equal. However, this operator only checks if the two arrays have the same keys and values, and it doesn't consider the order of the elements.

Here's an example of how you can use the == operator to check if two arrays are equal:

<?php

$array1 = [1, 2, 3, 4];
$array2 = [1, 2, 3, 4];

if ($array1 == $array2) {
    echo "The arrays are equal.";
} else {
    echo "The arrays are not equal.";
}