Page 1 of 1

For a tag system, how to compare 2 arrays of added/deleted

Posted: Thu Dec 16, 2010 8:51 am
by justulike
array1 = apple, orange, mango, melon

array2 = apple, orange, banana, watermelon, pineapple

how to compare 2 arrays and get the changes of:
1. newly added
2. deleted

like the above 2 arrays, the original array 1 contains 4 items , and then i wanna change it to array2 , delete mango and melon, add watermelon and pineapple.
i need to find out a result like this:

deleted : array1[2] , array1[3]
newly add: array2[2] , array2[3] , array1[4]

----------
more explaination for this , that i wanna create a tag system, that user able to add and delete current tag attached to a post.
but i dont know how to compare the 2 array and get the desired result.

can anyone help me plz

Re: For a tag system, how to compare 2 arrays of added/delet

Posted: Thu Dec 16, 2010 9:05 am
by xahoidenct
newly add:

Code: Select all

$result = array_diff_assoc($array1, $array2);
print_r($result);
deleted

Code: Select all

foreach($array1 as $key=> $val)
{
if( !array_search($val, $array2))
{
   echo "array1[$key]";
}
}

Re: For a tag system, how to compare 2 arrays of added/delet

Posted: Thu Dec 16, 2010 1:00 pm
by pickle
Actually it's a bit simpler:

Code: Select all

$deleted = array_diff($array1,$array2);
$added = array_diff($array2,$array1);