Reputation: 558
How to find what items are removed from last state array list and what items a add to new one? My arrays:
$arrayOld = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
$arrayNew = ["Z", "B", "C", "D", "E", "F", "G", "H", "I", "J", "Y"];
Explanation:
I have an array called $arrayOld
, User do some modification on the list and post a new array to the server and i want to know what items are removed from first array and what items are new!
Thanks
Upvotes: 0
Views: 835
Reputation: 558
You can simply find those using array_diff:
$arrayOld = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"];
$arrayNew = ["Z", "B", "C", "D", "E", "F", "G", "H", "I", "J", "Y"];
$removes = array_diff($arrOld, $arrNew);
print_r($removes); // A , K
$adds = array_diff($arrNew,$arrOld);
print_r($adds); // Z , Y
As per php.net docs:
array_diff — Computes the difference of arrays
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
Upvotes: 2
Reputation: 616
use the diff function it will show all the different with the index of the change items
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");
$result=array_diff($a1,$a2,$a3);
print_r($result);
the result will be :
Array ( [b] => green [c] => blue );
Upvotes: 0
Reputation: 642
array_diff would be a solution,
Get adds,
$new_elements = array_diff($arrayNew, $arrayOld);
print_r($new_elements); // first parameter should be new array
and second one should be old
Get Removals,
$old_elements = array_diff($arrayOld, $arrayNew);
print_r($old_elements); // Here first parameter should be old array
and second one should be new
Upvotes: 0