0

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"?

2 Answers 2

3

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

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.