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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
justulike
Forum Newbie
Posts: 1
Joined: Thu Dec 16, 2010 8:36 am

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

Post 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
xahoidenct
Forum Newbie
Posts: 1
Joined: Thu Dec 16, 2010 8:49 am

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

Post 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]";
}
}
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

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

Post by pickle »

Actually it's a bit simpler:

Code: Select all

$deleted = array_diff($array1,$array2);
$added = array_diff($array2,$array1);
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply