Backend Development 5 min read

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:

<code>mixed end(array &$array)</code>

Here $array can be either an indexed or associative array. The function returns the last value of the array.

Example with an indexed array:

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

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:

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

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

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

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

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.

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

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