Remove value from array - by value

3609 views php
6

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

answered question

Try unset($words[“string 1”]

array_diff_key()

2 Answers

10

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

posted this
0

You could do a simple unset:

foreach($remove_words as $key) {
    unset($words[$key]);
}

// Result:
Array ( 
    [string 1] => 4 
    [string 3] => 3 
    [string 5] => 8 
    [string 6] => 2 
    [string 7] => 10 
    [string 8] => 1 
)

posted this

Have an answer?

JD

Please login first before posting an answer.