Ravi Kadia
Ravi Kadia

Reputation: 275

How to remove an array element from compare to other array element?

I have two arrays. I need to remove an element from the first array when the element is included in the second array.

e.g.:

$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");

$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");

$Result = array("apple"=>"7","strawberry"=>"9");

I've used the following code but it is not working:

foreach($Second as $key){
    $keyToDelete = array_search($key, $First);
    unset($First[$keyToDelete]);
}
print_r($First);

Upvotes: 0

Views: 1047

Answers (2)

rharvey
rharvey

Reputation: 2005

You're close!

Firstly,

foreach ($Second as $key)

will only give you the value. To get the key you have to do

foreach ($Second as $key => $value)

Loop through the $Second array and then if they key exists (use isset) in $First array remove it using unset. $Second will then be the same as $Results

foreach ($Second as $key => $value) {
    if (isset($First[$key])) {
        unset($First[$key]);
    }
}

Alternatively, if you wanted to keep $First and $Second as they are then you can do the following:

foreach ($Second as $key => $value) {
    if (!isset($First[$key])) {
        $Results[$key] = $value;
    }
}

Upvotes: 2

Mark
Mark

Reputation: 1417

Use array_diff_key - http://php.net/manual/en/function.array-diff-key.php

$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");
$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");
$Result = array_diff_key($First, $Second);

Upvotes: 7

Related Questions