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.
<?php
$array = array("your array");
$array = array_diff($array, ["element you want to delete"]);
?>
Create your array in the variable $array
and then where I have put 'element you want to delete' you put something like: "a". And if you want to delete multiple items then: "a", "b".
unset($array[$index]);
To avoid doing a search one can play around with array_diff
:
$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11
In this case one doesn't have to search/use the key.
If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):
$my_array = array(
"key1" => "value 1",
"key2" => "value 2",
"key3" => "value 3",
"key4" => "value 4",
"key5" => "value 5",
);
$to_remove = array("key2", "key4");
$result = array_diff_key($my_array, array_flip($to_remove));
print_r($result);
Output:
Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 )
Follow the default functions:
unset()
destroys the specified variables. For more info, you can refer to PHP unset
$Array = array("test1", "test2", "test3", "test3");
unset($Array[2]);
The array_pop()
function deletes the last element of an array. For more info, you can refer to PHP array_pop
$Array = array("test1", "test2", "test3", "test3");
array_pop($Array);
The array_splice()
function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice
$Array = array("test1", "test2", "test3", "test3");
array_splice($Array,1,2);
The array_shift()
function removes the first element from an array. For more info, you can refer to PHP array_shift
$Array = array("test1", "test2", "test3", "test3");
array_shift($Array);