Using PHP end() Function to Retrieve the Last Element of an Array

This article explains the PHP end() function, its syntax, return values, and demonstrates how to use it with both indexed and associative arrays, including combined usage with reset() for reverse traversal, providing clear code examples for each scenario.

php Courses
php Courses
php Courses
Using PHP end() Function to Retrieve the Last Element of an Array

PHP is a widely used language for web development, and the end() function is a built‑in utility that returns the last element of an array while moving the internal array pointer to that element.

The basic usage of end() is to pass an array variable by reference; the function returns the final value or false if the array is empty or an error occurs.

Syntax: mixed end(array &$array) Here $array can be either an indexed or associative array. The function returns the last value of the array.

Example with an indexed array:

$numbers = array(1, 2, 3, 4, 5);
$lastNumber = end($numbers);
echo $lastNumber; // outputs 5

In this example, end() moves the internal pointer of $numbers to the last element and assigns its value to $lastNumber, which is then printed.

Example with an associative array:

$fruits = array(
  "apple"  => "red",
  "banana" => "yellow",
  "orange" => "orange"
);
$lastFruitColor = end($fruits);
echo $lastFruitColor; // outputs "orange"

The function moves the pointer of $fruits to the last key/value pair and returns the value.

Combining end() with reset() for reverse traversal:

$colors = array("red", "green", "blue", "yellow");
end($colors);
while ($color = current($colors)) {
  echo $color . " ";
  if ($color == "blue") {
    reset($colors);
  }
}

This snippet moves the pointer to the last element, iterates backwards using current(), and resets to the first element when the value "blue" is encountered, allowing traversal from the end.

In summary, the end() function is a practical tool for obtaining the last element of both indexed and associative arrays, and when paired with functions like reset() it enables flexible array navigation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPArrayTutorialpointerend()
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.