Skip to content
Advertisement

PHP: Built-in function to check whether two Array values are equal ( Ignoring the order)

Is there a built-in function for PHP for me to check whether two arrays contain the same values ( order not important?).

For example, I want a function that returns me true for the following two inputs:

array('4','5','2') 
array('2','4','5')

Edit: I could have sorted the two arrays and compare them, but as I am such a lazy guy, I would still prefer a one-liner that I can pull out and use.

Advertisement

Answer

array_diff looks like an option:

function array_equal($a1, $a2) {
  return !array_diff($a1, $a2) && !array_diff($a2, $a1);
}

or as an oneliner in your code:

if(!array_diff($a1, $a2) && !array_diff($a2, $a1)) doSomething();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement