2

I have an array of keys and values (words and their occurrences). I would like to remove certain keys (words). I have those words in another array. How do I filter out those word and create a new array?

I have tried this - but it doesn't remove the strings:

<?php
$words = array(
    'string 1' => 4,
    'string 2' => 6,
    'string 3' => 3,
    'string 4' => 3,
    'string 4' => 9,
    'string 5' => 8,
    'string 6' => 2,
    'string 7' => 10,
    'string 8' => 1
);

$remove_words = array(
    'string 4',
    'string 2'
);

$new_array = array_diff($words, $remove_words);

print_r($new_array);
?>

I would expect an output like this:

$new_array = array(
    'string 1' => 4,
    'string 3' => 3,
    'string 5' => 8,
    'string 6' => 2,
    'string 7' => 10,
    'string 8' => 1
);
4
  • Try unset($words[“string 1”] Commented Nov 4, 2018 at 16:58
  • possible duplicate of: stackoverflow.com/questions/7884991/… Commented Nov 4, 2018 at 16:58
  • array_diff_key() Commented Nov 4, 2018 at 16:59
  • Your array definition has repeated keys, these will clobber previously defined elements. Commented Nov 4, 2018 at 18:41

1 Answer 1

3

You can use array_flip() to change $remove_words values to keys, and then use array_diff_key(). Try:

$new_array = array_diff_key($words, array_flip($remove_words));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.