$input=array(a,b,c,d,e,f,g);
// Remove 4th element ( 0 indexed )
unset($input[3]);
while (list ($key, $val) = each ($input)) {
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.
while (list ($key, $val) = each ($new_array)) {
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);
unset($input[array_search('d',$input)]);
while (list ($key, $val) = each ($input)) {
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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.