How to use Array Indexing In PHP
The basic method to access the first and last elements of an array is by using element indexing. The array indexing starts with 0.
Example: In this approach, we directly access the first element using $arr[0] and the last element using $arr[count($arr) – 1].
<?php
// Get First and Last Array Elements
function getFirstAndLast(&$arr) {
$first = $arr[0];
$last = $arr[count($arr) - 1];
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