LAST UPDATED: AUGUST 4, 2021
How to delete an element from an array in PHP?
Answer: Using unset()
function
We can delete an array element using PHP unset() function. This function unsets the variable or we can say it destroys the variable.
When the unset()
function is called inside the user-defined function then it unsets the local variable. If we want to destroy the global variable inside the user-defined function we have to use the $GLOBALS to unset the global variable.
Example: Using unset()
function
In the given example, we have used the unset()
function to remove the array element from the given array.
<!DOCTYPE html>
<html>
<head>
<title>Delete an element from the array</title>
</head>
<body>
<?php
$arr1 = array("HTML", "CSS", "JavaScript", "PHP");
unset($arr1["2"]);
print_r($arr1);
?>
</body>
</html>
Output
Array ( [0] => HTML [1] => CSS [3] => PHP )
As you can see in the above output, you have noticed that unset()
function does not rearrange the index of the existing elements. To resolve this problem we use the splice() function.
Using splice()
function
The splice()
function is used to remove the array elements and returns an array with the removed elements. We can also replace the removed element with the new element using this function.
Also, the splice()
method arranges the indexes of the element after removing the elements from the array.
Example: Using splice()
function
In the given example, we have removed the array element using the splice()
function.
<!DOCTYPE html>
<html>
<head>
<title>Delete an element from the array</title>
</head>
<body>
<?php
$arr = array("HTML", "CSS", "JavaScript", "PHP");
array_splice($arr, 1, 1);
print_r($arr);
?>
</body>
</html>
Output
Array ( [0] => HTML [1] => JavaScript [2] => PHP )
Conclusion
In this lesson, we have learned how to delete an element from the array. There are several methods to delete an array element but we have discussed the two pre-defined functions, these functions are:
unset()
function which unset or destroys the array element.
splice()
function removes the array element from the given array and returns the new array.