How to use array_shift() and array_pop() Function In PHP
We can use array_shift() and array_pop() to retrieve and remove the first and last elements of an array, respectively.
Example: The array_shift($arr) removes and returns the first element, and array_pop($arr) removes and returns the last element. Note that this method modifies the original array by removing these elements.
<?php
// Get First and Last Array Elements
function getFirstAndLast(&$arr) {
$first = array_shift($arr);
$last = array_pop($arr);
return [$first, $last];
}
// Driver code
$arr = [10, 20, 30, 40, 50];
list($first, $last) = getFirstAndLast($arr);
echo "First Element: $first, Last Element: $last";
?>
Output
First Element: 10, Last Element: 50
Get the First & Last Item from an Array in PHP
We will get the first and last elements of an array in PHP. This can be particularly useful in scenarios like processing data, working with queues, or implementing specific algorithms.
Below are the approaches to get the first and last items from an array in PHP:
Table of Content
- Using Array Indexing
- Using reset() and end() Functions
- Using array_shift() and array_pop() Function
Contact Us