title: Most efficient way to compare arrays in PHP by order?
body: <p>Take these two arrays in PHP:</p>
  
  <pre><code>$array1 = [
      2 =&gt; 'Search',
      1 =&gt; 'Front-End / GUI'
  ];
  $array2 = [
      1 =&gt; 'Front-End / GUI',
      2 =&gt; 'Search'
  ];
  </code></pre>
  
  <p>Most of the array comparison functions do not care about order. Doing an <code>array_diff</code> will result in an empty array.</p>
  
  <p>What's the most efficient / shortest / cleanest way to compare two arrays with regard to order and:</p>
  
  <ol>
  <li>show whether or not they are equal (true / false)?</li>
  <li>show the difference (such as for PHPUnit)?</li>
  </ol>
  
  <p>Running <code>$this-&gt;assertEquals( $array1, $array2 );</code> in PHPUnit ideally should yield something like:</p>
  
  <pre><code>Failed asserting that two arrays are equal.
  --- Expected
  +++ Actual
  @@ @@
   Array (
  -    2 =&gt; 'Search'
  -    1 =&gt; 'Front-End / GUI'
  +    1 =&gt; 'Front-End / GUI'
  +    2 =&gt; 'Search'
   )
  </code></pre>
  
  <h2>Update - Solution</h2>
  
  <p>This generates a sort-of diff only if all elements are same, just in different order.
  PHPUnit Tests:</p>
  
  <pre><code>public function test...() {
      $actual = someCall();
      $expected = [...];
  
      // tests for same elements
      $this-&gt;assertEquals( $expected, $actual );
  
      // tests for same order
      $diff = $this-&gt;array_diff_order( $expected, $actual );
      $this-&gt;assertTrue( $expected === $actual, "Failed asserting that two arrays are equal order.\n--- Expected\n+++ Actual\n@@ @@\n Array(\n$diff )" );
  }
  
  private function array_diff_order( $array1, $array2 ) {
      $out = '';
      while ((list($key1, $val1) = each($array1)) &amp;&amp; (list($key2, $val2) = each($array2)) ) {
          if($key1 != $key2 || $val1 != $val2) $out .= "-    $key1 =&gt; '$val1' \n+    $key2 =&gt; '$val2'\n";
      }
      return $out;
  }
  </code></pre>