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
);
Meek
  • 2,796
  • 7
  • 35
  • 57

1 Answers1

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));
Madhur Bhaiya
  • 27,326
  • 10
  • 44
  • 54