PHP Get First and Last Element of Array Example

By Hardik Savani May 14, 2024 Category : PHP

Hello Dev,

This detailed guide will cover php get first and last element of array. let's talk about php get the first element in an array without a key. You can understand the concept of getting the first and last element of an array in php. We will help you with some examples of php array get first and last element examples.

In this example, reset() is used to move the internal pointer to the beginning of the array and return the first element, while end() is used to move the internal pointer to the end of the array and return the last element.

index.php

<?php

/* Sample array */

$myArray = array("apple", "banana", "orange", "grape", "kiwi");

/* Get the first element */

$firstElement = reset($myArray);

/* Get the last element */

$lastElement = end($myArray);

/* Output the results */

echo "First element: " . $firstElement . "\n";

echo "Last element: " . $lastElement . "\n";

?>

Output:

First element: apple

Last element: kiwi

I hope it can help you...

Tags :
Shares