PHP Get First and Last Element of Array Example

PHP Get First and Last Element of Array Example

  • Post category:PHP
  • Post comments:1 Comment

Learn how to efficiently retrieve the first and last elements of an array in PHP with this comprehensive guide. Whether you’re a beginner or an experienced developer, this tutorial will walk you through the simplest methods to access array elements in PHP. Enhance your coding skills with practical examples, tips, and best practices for working with PHP arrays. Perfect for PHP developers and web development enthusiasts looking to streamline data handling in their applications. You Can Learn Laravel Livewire CRUD Application Example

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..

This Post Has One Comment

Leave a Reply