PHP: How to remove specific element from an array?
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.