PUBLISHED ON: AUGUST 4, 2021
How to remove the first element from an array in PHP?
Answer: Using array_shift()
Function
We can remove the first element of an array using the array_shift()
function. This is a predefined PHP function that takes an array as its input and removes the first element of the input array. It and returns the value of the removed element.
If the given array is empty or the value passed as an argument is not an array, then the returned value is NULL.
Example: Removing using array_shift()
function
In the given example, we have removed the first array element from the given array $arr using the array_shift()
function.
<!DOCTYPE html>
<html>
<head>
<title>Removing first element of an array</title>
</head>
<body>
<?php
$arr = array("C++", "C", "JavaScript", "jQuery", "PHP");
$new_arr = array_shift($arr);
print_r($new_arr);
?>
</body>
</html>
C++
Using array_slice()
Function
The array_slice()
function is used when we want to remove the first element but also want to preserve the existing array. This function creates a new array instead of modifying the existing one.
Example: Removing using array_slice()
Function
In the given example, we have removed the first array element from the given array $arr using array_slice()
function.
<!DOCTYPE html>
<html>
<head>
<title>Removing first element of an array</title>
</head>
<body>
<?php
$arr = array("C++", "C", "JavaScript", "jQuery", "PHP");
$new_arr = array_slice($arr, 1);
print_r($new_arr);
?>
</body>
</html>
Array ( [0] => C [1] => JavaScript [2] => jQuery [3] => PHP )
Conclusion
In this lesson, we have discussed how to remove the first element of an array in PHP. We discussed two methods to remove the first element from the given array. At first, we have used the array_shift()
function and then we used the array_slice()
method to remove the first element from the given array. Both the function are predefined functions offered by PHP.