ItSolutionStuff.com

PHP Get First and Last Element of Array Example

By Hardik Savani • May 14, 2024
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...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Convert Array to XML in PHP?

Read Now →

How to Convert Collection to Array in Laravel?

Read Now →

How to Convert String to Array Conversion in Laravel?

Read Now →

PHP Check If Array Has Duplicate Values Example

Read Now →

How to Get Duplicate Values from Array in PHP?

Read Now →

How to Find Array Length in PHP?

Read Now →

How to Check Key Exists in Array in PHP?

Read Now →

How to Get First 5 Elements of Array in PHP?

Read Now →

How to Get First 2 Elements of Array in PHP?

Read Now →

How to Get Last 10 Elements of Array in PHP?

Read Now →

How to Get Last Element of Array in PHP?

Read Now →

How to Get First Element of Array in PHP?

Read Now →

How to Store Array in Database Laravel?

Read Now →