2

I have two key value pair arrays, one is the original, the other an array of key value pairs that need to be removed. I need to remove a specific combination, ie $removeArray would contain:

Array([Word] => 78)

I've tried:

foreach($removeArray as $key => $value){unset($originalArray[$key][$value]);}

This doesn't work at all. I need to remove based off an exact key value pair match.


EDIT:

Original

Array ( [distribution] => 25 [watch] => 25 [electricity] => 25 [timepiece] => 8 [wristwatch] => 25 [energy] => 8 [transmission] => 8 [clock] => 16 ) 

Remove

Array ( [timepiece] => 8 [energy] => 8 [watch] => 17 ) 

Result

Array ( [distribution] => 25 [watch] => 25 [electricity] => 25 [wristwatch] => 25  [transmission] => 8 [clock] => 16 ) 

NOTE:

[watch] => 25 is not affected, because it is not equal to [watch] => 17

3
  • 2
    Can you post two array and expected result ? Commented May 12, 2016 at 10:03
  • if($key == "Word"){unset($originalArray[$key][$value]);} Commented May 12, 2016 at 10:05
  • Posted example arrays. Commented May 12, 2016 at 10:07

3 Answers 3

5

You can use array_diff_assoc() for that, that compares both the values and the keys:

$result = array_diff_assoc($original, $to_remove);

Example code:

$removeArray = array(
    'word'=>45,
    'number'=>112,
    'sign'=>2167
);

$originalArray = array(
    'lorem'=>2343,
    'ipsum'=>433,
    'word'=>78,
    'number'=>112,
    'sign'=>2167
);

$result = array_diff_assoc($originalArray, $removeArray);

Result:

Array
(
    [lorem] => 2343
    [ipsum] => 433
    [word] => 78
)
Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! Not sure how efficient it is, but it's the simplest answer. Thanks! :)
1

try this

foreach($removeArray as $key => $value){
    if($value==$originalArray[$key])
        unset($originalArray[$key]);
}

Comments

0

You can check like:

if($originalArray[$key] == "78" && $key = "Word") {
unset($originalArray[$key]);
}

Comments

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.