简体   繁体   中英

How can I determine the elements in an array that do not exist in another array?

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.

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.

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)

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
)

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);

Live Example

在此处输入图片说明

and

$result = array_diff($parts1 , $parts2 );

print_r($result);

LIVE example

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM