W3docs

PHP - Check if two arrays are equal

You can use the array_diff() function to 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. To ensure true equality, you must check both directions. If both array_diff($array1, $array2) and array_diff($array2, $array1) return empty arrays, 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:

How to check if two arrays are equal in PHP?

<?php

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

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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 both input 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:

How to check if two arrays are equal in PHP using array_intersect() function?

<?php

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

if (array_intersect($array1, $array2) === $array1 && array_intersect($array2, $array1) === $array2) {
    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 checks if the two arrays have the same key/value pairs regardless of order. For strict comparison including order and data types, use the === operator.

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

How to check if two arrays are equal in PHP using "===" operator?

<?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.";
}

Note: If you need to compare both keys and values strictly, consider using array_diff_assoc(), which returns differences including key mismatches.