How to check if two arrays are equal in PHP with exmaples

How to check if two arrays are equal in PHP with exmaples

In this article let’s understand how to check if two arrays are equal in PHP with exmaples.

So mainly there are two operators in PHP which are “==” && “===” for equality comparison. Depending on our need how we want to check array as with only values or with key-value etc.

Lets check few examples below to understand the concept :

Example 1 :

$array1 = array(1, 2, 3);
$array2 = array(3, 2, 1);

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

// Output : The arrays are equal.

Example 2 :

$array1 = array("a" => 1, "b" => 2, "c" => 3);
$array2 = array("c" => 3, "b" => 2, "a" => 1);

if ($array1 == $array2) {
    echo "Arrays are equal.\n";
} else {
    echo "Arrays are not equal.\n";
}

// Output : The arrays are equal.

Example 3 :

$array1 = array(1, 2, 3);
$array2 = array("1", "2", "3");

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

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

//Output : 
The arrays are equal.
The arrays are not identical.

Example 4 :

$array1 = array("apple", "banana", "orange");
$array2 = array("banana", "orange", "apple");

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

// Output :
The arrays are equal.

Example 5 :


$array1 = array("1", "2", "3");
$array2 = array("1", "2", "3");

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

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

//Output : 
The arrays are equal.
The arrays are identical.

Hope these examples help you understand and choose your way to use it how you need.

That’s it on how to check if two arrays are equal in PHP with exmaples.

See other articles on PHP here.