nachete
nachete

Reputation: 59

Unset value from array by value, not key

I have the following array:

Array (
    [0] => 1
    [1] => 2
    [2] => 2
    [3] => 4
    [4] => 4
    [5] => 8)

I want to remove some items of the array but by value, not by key. How I can do that if I want to remove all the items with the value "4", or with the value "x"?

Upvotes: 0

Views: 91

Answers (2)

Bernhard
Bernhard

Reputation: 1870

you could try it this way:

<?php

 $data = array('haha', 'hehe', 'hihi', 'gtfo', 'hoho', 'huhu');

 $data = preg_grep('/^(?!gtfo).*$/', $data);

 print_r($data);

?>

Output:

Array
(
    [0] => haha
    [1] => hehe
    [2] => hihi
    [4] => hoho
    [5] => huhu
)

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

Use array_search

$key = array_search(4, $arr);
unset($arr[$key]);

If occurences of value in array is more than once use array_keys:

$keys = array_keys($arr, 4);
foreach ($keys as $k)
    unset($arr[$k]);

Upvotes: 3

Related Questions