unset() removes an array element by key without reindexing the remaining numeric keys. Use array_values() afterwards only when you explicitly need a new zero-based index sequence.
$items = ['red', 'green', 'blue', 'yellow'];
unset($items[1]);
print_r($items);
$reindexed = array_values($items);
print_r($reindexed);When removing by value, first find the key with array_search() and test the result with !== false before calling unset().
$input=array('a','b','c','d','e','f','g');
// Remove 4th element ( 0 indexed )
unset($input[3]);
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
As we are deleting the third element (4th on 0 index) the output of above code is here.
0 -> a
1 -> b
2 -> c
4 -> e
5 -> f
6 -> g
We can remove an element from an array by using unset command.
unset($input[3]);
Here we are removing the element with key=3. If the array has 7 elements and if try to delete 9th element then unset command will not return any error but nothing will be deleted.
$new_array=array_diff($input,array("d"));
We can also use like this to remove more elements by using its value.
$remove=array('c','f');
$new_array=array_diff($input,$remove);
Display & check our elements after removal like this.
foreach ($new_array as $key => $val) {
echo "$key -> $val <br>";}
The output of the above command is here
0 -> a
1 -> b
3 -> d
4 -> e
6 -> g
You can read how unset a variable here.
$input=array('a','b','c','d','e','f','g');
$key = array_search('d', $input, true);
if ($key !== false) {
unset($input[$key]);
}
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
4 -> e
5 -> f
6 -> g
Sometimes, you may want to remove elements from an array based on a condition:
$arr = array(10, 20, 30, 40, 50);
foreach ($arr as $key => $value) {
if ($value % 20 == 0) {
unset($arr[$key]);
}
}
print_r($arr); // Output: Array ( [0] => 10 [2] => 30 [4] => 50 )
You can completely remove the array using *unset()*:
$arr = array(1, 2, 3);
unset($arr);
echo isset($arr) ? "Array exists" : "Array is unset"; // Output: Array is unset
$arr = array("name" => "John", "age" => 30, "city" => "NY");
unset($arr['age']);
print_r($arr); // Output: Array ( [name] => John [city] => NY )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.