Is there an easy way to delete an element from an array using PHP, such that foreach ($array)
no longer includes that element?
I thought that setting it
If the index is specified:
$arr = ['a', 'b', 'c'];
$index = 0;
unset($arr[$index]); // $arr = ['b', 'c']
If the index is NOT specified:
$arr = ['a', 'b', 'c'];
$index = array_search('a', $arr); // search the value to find index
if($index !== false){
unset($arr[$index]); // $arr = ['b', 'c']
}
The if
condition is necessary
because if index
is not found, unset()
will automatically delete
the first element of the array which is not what we want.