Veera
Veera

Reputation: 33182

Finding out the common / uncommon elements between two Arrays in PHP

Consider I have two arrays:

$friends = Array('foo', 'bar', 'alpha');
$attendees = Array('foo', 'bar');

Now I need to populate a new array $nonattendees which contains only the elements which are in $friends array and not in $attendees array. i.e, $nonattendees array should be populated with 'alpha'.

Is there any in built array operation available in PHP to achieve the above functionality or should I write my own for loops?

Upvotes: 1

Views: 4412

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157919

http://php.net/manual/en/ref.array.php has plenty of functions for you.
array_intersect() or array_diff() for example

Manual pages are always better choice for such a direct questions.

Upvotes: 0

sam
sam

Reputation: 376

// difference items code 
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);

// common items code //
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

Upvotes: 3

MiffTheFox
MiffTheFox

Reputation: 21575

array_diff seems to be what you're looking for.

$nonattendees = array_diff($friends, $attendees);

Upvotes: 5

Related Questions