Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to remove specific element from an array?

Tags:

arrays

php

People also ask

How can I remove a specific item from an array PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an item from an array by value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.


Use array_search to get the key and remove it with unset if found:

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}

array_search returns false (null until PHP 4.2.0) if no item has been found.

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

Use array_diff() for 1 line solution:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loop.


if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

If you are using a plain array here (which seems like the case), you should be using this code instead:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

Supposingly we have an array and use array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.


You can use array filter to remove the items by a specific condition on $v:

$arr = array_filter($arr, function($v){
    return $v != 'some_value';
});

Just u can do single line .it will be remove element from array


$array=array_diff($array,['strawberry']);