PHP Get First and Last Element of Array Example
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert Array to XML in PHP?
- How to Convert Collection to Array in Laravel?
- How to Convert String to Array Conversion in Laravel?
- PHP Check If Array Has Duplicate Values Example
- How to Get Duplicate Values from Array in PHP?
- How to Find Array Length in PHP?
- How to Check Key Exists in Array in PHP?
- How to Get First 5 Elements of Array in PHP?
- How to Get First 2 Elements of Array in PHP?
- How to Get Last 10 Elements of Array in PHP?
- How to Get Last Element of Array in PHP?
- How to Get First Element of Array in PHP?
- How to Store Array in Database Laravel?