Skip to content

Instantly share code, notes, and snippets.

@jmc734
Last active December 24, 2015 05:18
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 jmc734/6749235 to your computer and use it in GitHub Desktop.
Save jmc734/6749235 to your computer and use it in GitHub Desktop.
<?php
function compare_keys($a, $b) {
if(abs($a) == abs($b)) return 0;
return (abs($a) > abs($b))?1:-1;
}
function compare_values($a, $b){
$tempA = is_array($a)?$a[0]:$a;
$tempB = is_array($b)?$b[0]:$b;
if($tempA == $tempB) return 0;
return ($tempA > $tempB)?1:-1;
}
$test1 = array(
1 => "a",
2 => "b",
3 => "c"
);
$test2 = array(
-1 => "a",
-2 => "b",
-3 => "c"
);
$test3 = array(
1 => array("a"),
2 => array("b"),
3 => array("c")
);
/** Test 1
* We are find the difference between arrays $test1 and $test2
* array_diff_uassoc will use the compare_keys function for the keys and check the values for equality and
* array_udiff_assoc will use the compare_keys function for the values and check the keys for equality.
* The compare_keys function compares the absolute values of the parameter. Therefore, when we use array_diff_uassoc
* it is like comparing identical arrays and we should get an empty result.
*/
echo "<hr/>Test 1<hr/><br/>";
echo "array_diff_uassoc<br/><pre>";
print_r(array_diff_uassoc($test1, $test2, "compare_keys"));
/*
Array
(
)
*/
echo "</pre><hr/>array_udiff_assoc<br/><pre>";
print_r(array_udiff_assoc($test1, $test2, "compare_keys"));
/*
Array
(
[1] => a
[2] => b
[3] => c
)
*/
/** Test 2
* We are going to find the differences between arrays $test1 and $.
* array_diff_uassoc will check the values for equality and compare the keys with the function compare_values.
* Therefore, we should get the entire contents of $test1 back.
*
* array_udiff_assoc will check the keys for equality and compare the values with the function compare_values.
* This function checks if the parameters are arrays and if so uses the first value.
* For example, if "a" is compared to array("a"), the returned value would be 0.
*/
echo "</pre><br/><hr/>Test 2<hr/><br/>";
echo "array_diff_uassoc<br/><pre>";
print_r(array_diff_uassoc($test1, $test3, "compare_values"));
/*
Array
(
[1] => a
[2] => b
[3] => c
)
*/
echo "</pre><hr/>array_udiff_assoc<br/><pre>";
print_r(array_udiff_assoc($test1, $test3, "compare_values"));
/*
Array
(
)
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment