To check if two arrays have the same elements regardless of order in PHP, you can sort both arrays and then compare them using the ==
operator.
In this example,
$arr1
and $arr2
with the same elements but in different order.sort()
function.==
operator and store the result in the variable $equal1
.$equal1
to the output.<?php
$arr1 = [1, 2, 3];
$arr2 = [3, 1, 2];
sort($arr1);
sort($arr2);
$equal1 = $arr1 == $arr2;
echo $equal1 ? 'true' : 'false';
?>
true
In this example,
$arr3
and $arr4
with different elements.sort()
function.==
operator and store the result in the variable $equal2
.$equal2
to the output.<?php
$arr3 = [1, 2, 3];
$arr4 = [4, 5, 6];
sort($arr3);
sort($arr4);
$equal2 = $arr3 == $arr4;
echo $equal2 ? 'true' : 'false';
?>
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in PHP language with well detailed examples.