Suppose there are arrays

$a = array(1,2,3); $b = array(3,2,1); 

How can I determine if the values ​​are the same in these arrays without enumerating one of them? I need a solution like

 if($a == $b){ } 

If this is of course. And I can’t attach such a method to an existing function

 foreach ($a as $key => $value) { if (in_array($value, $b)) { } } 

I need to get at the output not the differences of the arrays, but their equality or non-equality of the values ​​of the arrays.

3 answers 3

Fast implementation (better than your solution):

 $a = array(1, 2, 3); $b = array(3, 2, 1); function isEqually(&$a, &$b) { $i = sizeOf($a); $sizeB = sizeOf($b); if ($i !== $sizeB) { return false; } while ($i--) { if ($a[$i] !== $b[$i]) return false; } return true; } if (isEqually($a, $b)) { echo 'Равны'; } else { echo 'Не равны'; } 
  • Works faster on 0.00001 and yes. It will be useful. thank. - Shevtsov Eugene
  • @ShevtsovEugene is with 3 digits, but with large data sets? my win because I do not call it 2 times, and do not return an array which will then be compared with another array, etc. And it does not do a complete brute force array if an irrelevant element is immediately found. - Vasily Barbashev
  • @ShevtsovEugene It seemed to me that your question implied "equality" when some elements of the first array are in the second (of course in the same quantities), but the order is not important. Those. 123 equals 321. This answer implies a complete identity. What really interested you? - Mike
  • @ Vasily Barbashev By the way, if the arrays are large, it is very useful to declare the function isEqually(&$a, &$b) then the arrays will not be copied during transmission, which will also speed up the work - Mike
  • @Mike yes, that's right, I somewhere in some other post once wrote in the comments that it is better to transmit links, apparently not here)) Corrected the post - Vasily Barbashev

If it is necessary not to take into account the order of elements, but only their composition, then it is possible so:

 function array_values_equal($a, $b) { sort($a); sort($b); return $a === $b; } $a = array(1, 2, 3); $b = array(3, 2, 1); if (array_values_equal($a, $b)) { echo 'Равны'; } else { echo 'Не равны'; } 

    You can take a native function and compare the difference of arrays:

     $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); 

    result:

     Array ( [1] => blue )