Reputation: 22610
In Ruby I can do this:
fruit = ['banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava']
citrus = ['orange','lemon','lime','tangerine']
others = fruit - citrus
And others
will contain an array of non-citrus fruits.
How can I do this in PHP?
$fruit = array('banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava');
$citrus = array('orange','lemon','lime','tangerine');
$others = # NOW WHAT ?????
Do I need to iterate over each item in $citrus
and find its offset in $fruit
(if it exists in that array) and then unset it, and then use array_values() to fix the array's indices? Or is there a simpler, less error-prone way?
Please note: I'm not looking for the intersection of the arrays. I'm looking for a complement. This was originally closed as a duplicate of a question asking the former.
Upvotes: 1
Views: 182
Reputation: 5239
you can use array_diff()
:
$others = array_merge(array_diff($fruit, $citrus));
You would need to use array_merge to arrange the indices. See it in action here
$others
will contain these values:
Array
(
[0] => banana
[1] => apple
[6] => kiwi
[7] => mango
[8] => guava
)
Upvotes: 1
Reputation: 95101
You can just use array_diff
$fruit = array('banana','apple','tangerine','orange','lemon','lime','kiwi','mango','guava');
$citrus = array('orange','lemon','lime','tangerine');
$others = array_diff($fruit, $citrus);
var_dump($others);
Output
array
0 => string 'banana' (length=6)
1 => string 'apple' (length=5)
6 => string 'kiwi' (length=4)
7 => string 'mango' (length=5)
8 => string 'guava' (length=5)
Upvotes: 4
Reputation: 5283
this can be done by array_intersect and array_diff
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
$result = array_intersect($parts1 , $parts2 );
print_r($result);
and
$result = array_diff($parts1 , $parts2 );
print_r($result);
Upvotes: 0
Reputation: 145482
Yes, there is array_diff()
which does exactly that:
$others = array_diff($fruit, $citrus);
That'll leave you with:
Array
(
[0] => banana
[1] => apple
[6] => kiwi
[7] => mango
[8] => guava
)
Which seems to be the expected remainder after subtracting citrus fruits from other fruits.
Upvotes: 6