There are two ways to remove an element from the array in PHP.
- Unset() Method
- Array_splice() Method
Unset() Method
The unset() method is a built-in function in PHP that is used to remove or unset a single element from the array. Check out the syntax.
Example
<?php
$arr = array("john","mark", "noah", "peter");
unset($arr[2]);
print_r($arr);
?>
Output
Array (
[0] => jhon
[1] => mark
[3] => peter
)
Array_splice() Method
The array_splice function is used when you want to delete or remove or replace an element from the array.
Example
<?php
$top = ["a"=> "AI", "b"=>"Programming", "c"=>"Python",
"d"=> "PHP"];
array_splice($top, 2, 1);
echo "<pre>";
print_r($top);
echo "</pre>";
?>
Output
Array
(
[a] => AI
[b] => programming
[d] => php
)
Conclusion
In this tutorial, we discussed the two most helpful methods for removing an element from the array in PHP.
Top comments (0)