search for in the  
<eachextract>
Last updated: Thu, 19 May 2005

end

(PHP 3, PHP 4, PHP 5)

end --  Set the internal pointer of an array to its last element

Description

mixed end ( array &array )

end() advances array's internal pointer to the last element, and returns its value.

Example 1. A simple end() example

<?php

$fruits
= array('apple', 'banana', 'cranberry');
echo
end($fruits); // cranberry
    
?>

See also current(), each(), prev(), next() and reset().



User Contributed Notes
end
12-May-2005 03:21
Fix for unknown writer of 29-aug-2002.
If you need to get a reference to the first or last element of an array, use these functions:

   function &first(&$array) {
       if (!is_array($array))
           return null;
       if (!count($array))
           return false; // like reset()
       reset($array);
       return $array[key($array)];
   }
      
   function &last(&$array) {
       if (!is_array($array))
           return null;
       if (!count($array))
           return false; // like end()
       end($array);
       return $array[key($array)];
   }

Example (watch out - use as &last() and &first()):

$a = array( 0 => 'less', 10 => 'ten', 20 => ' more');

if ($first = & first($a)) // not false or null
   $first = 'nothing';
if ($last = & last($a)) // not false or null
   $last = 'double';

Now $a is array( 0 => 'nothing', 10 => 'ten', 20 => ' double')
user at mail dot com
01-Mar-2005 09:29
It may be obvious, but if the array is empty, end() returns bool(false).
28-Aug-2002 08:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
28-Aug-2002 08:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}

<eachextract>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT