Skip to content

Instantly share code, notes, and snippets.

@toburger
Last active September 28, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toburger/f4ce94ea56b2333b687e to your computer and use it in GitHub Desktop.
Save toburger/f4ce94ea56b2333b687e to your computer and use it in GitHub Desktop.
PHP: Computes the difference of two arrays by value, not by key (like array_diff_ukey)
<?php
function diff($array1, $array2, $compare_func) {
return array_diff_ukey($array1, $array2, function($key1, $key2) use ($array1, $array2, $compare_func) {
if (!isset($array1[$key1])) return 1;
if (!isset($array2[$key2])) return -1;
return $compare_func($array1[$key1], $array2[$key2]);
});
}
<?php
$array1 = array(array("id" => 123), array("id" => 42));
$array2 = array(array("id" => 42), array("id" => 1423));
$difference = diff($array1, $array2, function($val1, $val2) {
//return $val1["id"] <=> $val2["id"]; PHP7
if ($val1["id"] == $val2["id"])
return 0;
else if ($val1["id"] > $val2["id"])
return 1;
else
return -1;
});
var_dump($difference);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment