I'm building application that tells user which are old and which are new bank notes when I increase sum with X. Everything is fine, but I'm wondering how I can now get list of added and removed items of array?
$old = array(1,5,10);
$new = array(1,5,1);
$added = array_diff($new,$old);
$removed = array_diff($old,$new);
And this is what code above returns:
$added
is array()
. Incorrect, it should be array([2] => 1)
.$removed
is array([2] => 10)
. Correct.What am I doing wrong, and how can I fix it?
$added = array_diff($new,$old);
In the above statement, array_diff()
compares $new
with $old
and returns the values in $new
that are not present in $old
. There is no such value, and hence it returns an empty array.
In short, array_diff()
doesn't work with duplicate values. You will have to write a custom function to achieve this. Here's an example:
function array_diff_once($array1, $array2) {
foreach($array2 as $val) {
if (false !== ($pos = array_search($val, $array1))) {
unset($array1[$pos]);
}
}
return $array1;
}
You can simply use it the same way you did before:
$added = array_diff_once($new,$old);
$removed = array_diff_once($old,$new);
print_r()
of these arrays would correctly output:
Array
(
[2] => 1
)
Array
(
[2] => 10
)
If you want to check the keys in addition to the values of an array, you should use array_diff_assoc() instead of array_diff()
:
<?php
$old = array(1,5,10);
$new = array(1,5,1);
$added = array_diff_assoc($new,$old);
$removed = array_diff_assoc($old,$new);
echo "<pre>
"; \\ prints array(1) { [2]=> int(1) }
var_dump($added);
var_dump($removed);
echo "</pre>
";
?>