To check if two arrays are equal in PHP, you can use the array_diff
function for arrays with the same elements and the ==
operator for arrays with different elements.
In this example,
$arr1
and $arr2
with the same elements.array_diff
function to check if the arrays are equal and store the result in the variable $equal1
.array_diff
function compares the values of two arrays and returns the difference.$equal1
is empty to determine if the arrays are equal.<?php
$arr1 = [1, 2, 3];
$arr2 = [1, 2, 3];
$equal1 = empty(array_diff($arr1, $arr2));
echo "Arrays are equal: " . ($equal1 ? 'true' : 'false');
?>
Arrays are equal: true
In this example,
$arr3
and $arr4
with different elements.==
operator to check if the arrays are equal and store the result in the variable $equal2
.==
operator checks if two arrays are equal in terms of key/value pairs, regardless of order.$equal2
to the console.<?php
$arr3 = [1, 2, 3];
$arr4 = [3, 2, 1];
$equal2 = $arr3 == $arr4;
echo "Arrays are equal: " . ($equal2 ? 'true' : 'false');
?>
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in PHP language with well detailed examples.