Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>UPDATE </p> <ul> <li><p><a href="https://stackoverflow.com/questions/2479963/how-does-array-diff-work/6700430#6700430">see below</a> for faster/better code. </p></li> <li><p>array_diff behaviour is much better in php 5.3.4, but still ~10 times slower than Leo's function.</p></li> <li><p>also it's worth noting that these functions are not strictly equivalent to <code>array_diff</code> since they don't maintain array keys, i.e. <code>my_array_diff(x,y) == array_values(array_diff(x,y))</code>. </p></li> </ul> <p>/UPDATE</p> <p>A better solution is to use <a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow noreferrer">hash maps</a></p> <pre><code>function my_array_diff($a, $b) { $map = $out = array(); foreach($a as $val) $map[$val] = 1; foreach($b as $val) if(isset($map[$val])) $map[$val] = 0; foreach($map as $val =&gt; $ok) if($ok) $out[] = $val; return $out; } $a = array('A', 'B', 'C', 'D'); $b = array('X', 'C', 'A', 'Y'); print_r(my_array_diff($a, $b)); // B, D </code></pre> <p>benchmark</p> <pre><code>function your_array_diff($arraya, $arrayb) { foreach ($arraya as $keya =&gt; $valuea) { if (in_array($valuea, $arrayb)) { unset($arraya[$keya]); } } return $arraya; } $a = range(1, 10000); $b = range(5000, 15000); shuffle($a); shuffle($b); $ts = microtime(true); my_array_diff($a, $b); printf("ME =%.4f\n", microtime(true) - $ts); $ts = microtime(true); your_array_diff($a, $b); printf("YOU=%.4f\n", microtime(true) - $ts); </code></pre> <p>result</p> <pre><code>ME =0.0137 YOU=3.6282 </code></pre> <p>any questions? ;)</p> <p>and, just for fun,</p> <pre><code>$ts = microtime(true); array_diff($a, $b); printf("PHP=%.4f\n", microtime(true) - $ts); </code></pre> <p>result</p> <pre><code>ME =0.0140 YOU=3.6706 PHP=19.5980 </code></pre> <p>that's incredible!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload