Now, to check if two arrays are equal, you can iterate over the arrays and check if for each index the value associated with the index in both arrays is the same or not. PHP has a built-in array operator (===) to check for the same, but the order of the array elements is not important here. When the order of the array elements is not important, two methods can be used to check if arrays are equal:
- Use the sort() function to sort an array element, and then use the equal operator.
- Use the array operator (==) in case of an associative array.
// Program for checking array equality using
// sort() and the equality operator
// Sample Arrays
$arr1
=
array
(4, 5,
’hello’
, 2.45, 3.56);
$arr2
=
array
(5, 2.45,
’hello’
, 3.56, 4);
// Sort array elements
sort (
$arr1
);
sort (
$arr2
);
// Test for equality
if
(
$arr1
==
$arr2
)
echo
"Both arrays are same"
;
else
echo
" Both arrays are not same "
;
// Sample Arrays
$arr3
=
array
( 5,
’car’
,
’ hello’
, 2.45, 3.56);
$arr4
=
array
(4, 2.45,
’hello’
, 3.56,
’engineer’
);
// Sort array elements
sort (
$arr3
);
sort (
$arr4
);
// Test for equality
if
(
$arr3
==
$arr4
)
echo
"Both arrays are same"
;
else
echo
" Both arrays are not same "
;
?>
Exit:Both arrays are same Both arrays are not same
Test for equality in an associative array.In case of an associative array, all elements have an index associated with them, so no sorting is required, the equality operator can be directly applied to test for equality. In fact, the equality operator compares the values corresponding to the index in both arrays, if all the index values are the same, then they are equal, otherwise they are not.Syntax:bool $arr1 == $arr2
In the case of an indexed array, the sort is performed to arrange the elements sequentially, whereas in the case of an associative array, the elements are already indexed, so the sort is no longer required.Program:PHP code to check equality of two associative arrays
// Program for checking associative array equality
// Sample Arrays
$arr1
=
array
(
’ first’
= >
’engineer’
,
’second’
= >
’for’
,
’last’
= >
’ide’
);
$arr2
=
array
(
’first’
= >
’ engineer’
,
’last’
= >
’ ide’
,
’second’
= >
’for’
);
// Test for equality
if
(
$arr1
==
$arr2
)
echo
"Both arrays are same"
;
else
echo
" Both arrays are not same "
;
// Sample Arrays
$arr3
=
array
(
’first’
= >
’ engineer’
,
’second’
= >
’for’
,
’last’
= >
’ ide ’
);
$arr4
=
array
(
’first’
= >
’ geek’
,
’second’
= >
’ for’
,
’last’
= >
’engineer’
);
// Test for equality
if
(
$arr3
==
$arr4
)
echo
"Both arrays are same"
;
else
echo
" Both arrays are not same "
;
?>
Exit:Both arrays are same Both arrays are not same