0

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

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

3 Comments

nice answer. +1 up
my bad, changed to array_diff_key - checked it right now, result is same as desired by OP
also change the top portion
2

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

4 Comments

if you unset then you lost data.
but in my case data comes from db and i just used for show with remove duplication.
Maybe it is possible to eliminate duplicates on database level?
@fraynekonok I have updated my answer. If the key does not exist then store in $Results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.