
Remove First Element from Array in PHP
To remove the first element from an array in PHP, you can use the array_shift()
function. array_shift()
removes the first element from the array and returns its value. The array keys will be reindexed automatically after removing the first element.
Here’s how you can use array_shift()
to remove the first element from an array:
$fruits = array("apple", "banana", "orange", "kiwi");
$removedElement = array_shift($fruits);
// Output the modified array
print_r($fruits);
// Output the removed element
echo "Removed Element: " . $removedElement;
Output:
Array
(
[0] => banana
[1] => orange
[2] => kiwi
)
Removed Element: apple
In the example above, we have an array $fruits
containing four elements. We use array_shift($fruits)
to remove the first element (“apple”) from the array. After removing the element, the array keys are reindexed, and the resulting array contains the remaining elements (“banana”, “orange”, and “kiwi”).
Keep in mind that using array_shift()
modifies the original array by removing its first element. If you want to keep the original array intact while creating a new array without the first element, you can use array slicing with array_slice()
:
$fruits = array("apple", "banana", "orange", "kiwi");
$modifiedArray = array_slice($fruits, 1);
// Output the modified array
print_r($modifiedArray);
// Output the original array remains unchanged
print_r($fruits);
Output:
Array
(
[0] => banana
[1] => orange
[2] => kiwi
)
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
)
In this case, $modifiedArray
contains the elements from index 1 to the end of the original $fruits
array, effectively excluding the first element. The original array $fruits
remains unchanged.