end

(PHP 4, PHP 5, PHP 7, PHP 8)

endPositionne le pointeur de tableau en fin de tableau

Description

end(array|object &$array): mixed

end() déplace le pointeur interne du tableau array jusqu'au dernier élément et retourne sa valeur.

Liste de paramètres

array

Le tableau. Ce tableau est passé par référence car il sera modifié par la fonction. Cela signifie que vous devez passer une vraie variable et non une fonction retournant un tableau, car actuellement, seules les variables peuvent être passées par référence.

Valeurs de retour

Retourne la valeur du dernier élément ou false si le tableau est vide.

Historique

Version Description
8.1.0 Soit convertir l'objet en un tableau en utilisant get_mangled_object_vars() d'abord, ou utiliser les méthodes fournies par une classe qui implémente Iterator, telle que ArrayIterator.
7.4.0 À partir de PHP 7.4.0, les instances de classes SPL sont traitées comme des objets vides sans propriétés au lieu d'appeler la méthode Iterator avec le même nom que cette fonction.

Exemples

Exemple #1 Exemple avec end()

<?php

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

?>

Voir aussi

  • current() - Retourne l'élément courant du tableau
  • each() - Retourne chaque paire clé/valeur d'un tableau
  • prev() - Recule le pointeur courant de tableau
  • reset() - Remet le pointeur interne de tableau au début
  • next() - Avance le pointeur interne d'un tableau
  • array_key_last() - Récupère la dernière clé d'un tableau

add a note

User Contributed Notes 11 notes

up
132
franz at develophp dot org
13 years ago
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

<?php
$a
= array();
$a[1] = 1;
$a[0] = 0;
echo
end($a);
?>

This will print "0".
up
35
jasper at jtey dot com
18 years ago
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
end($array);
return
key($array);
}
?>

Usage example:
<?php
$a
= array("one" => "apple", "two" => "orange", "three" => "pear");
echo
endKey($a); // will output "three"
?>
up
24
jorge at REMOVETHIS-2upmedia dot com
12 years ago
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc( $array ) { return end( $array ); }

$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
up
30
Anonymous
22 years ago
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:

<?php
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)];
}
?>
up
12
ivijan dot stefan at gmail dot com
10 years ago
I found that the function end() is the best for finding extensions on file name. This function cleans backslashes and takes the extension of a file.

<?php
private function extension($str){
$str=implode("",explode("\\",$str));
$str=explode(".",$str);
$str=strtolower(end($str));
return
$str;
}

// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo
extension($file); // txt
?>

Very simple.
up
-1
ken at expitrans dot com
19 years ago
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x
= array_keys(array('x' => 'y'));
echo
">> ".end($x)."\n";

?>
up
-3
Jason
11 years ago
$filename = 'somefile.jpg';

php v5.4 does not support the following statement.
echo end(explode(".", $filename)); // return jpg string

instead you have to split into 2 statements
$file = explode(".", $filename);
echo end ($file);
up
-4
Jacob
7 years ago
Attempting to get the value of a key from an empty array through end() will result in NULL instead of throwing an error or warning becuse end() on an empty array results in false:

<?php

$a
= ['a' => ['hello' => 'a1','world' => 'a2'],
'b' => ['hello' => 'b1','world' => 'b2'],
'c' => ['hello' => 'c1','world' => 'c2']
];
$b = [];

var_dump(end($a)['hello']);
var_dump(end($b)['hello']);
var_dump(false['hello']);

?>

Results in:

string(2) "c1"
NULL
NULL
up
-5
Sam Yong - hellclanner at live dot com
15 years ago
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while(
$i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
[0]=>
array(2) {
[0]=>
string(8) "764d8d20"
[1]=>
string(8) "85ee186d"
}
[1]=>
array(2) {
[0]=>
string(8) "c8c72466"
[1]=>
string(8) "a0fdccb2"
}
[2]=>
array(2) {
[0]=>
string(8) "3463a31b"
[1]=>
string(8) "589f6b63"
}
}

array(2) {
[0]=>
string(8) "3463a31b"
[1]=>
string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
up
-5
Aleksandr
6 years ago
<?php
$A
=[1];
print_r($A);
end($A[5]);
print_r($A);
?>

Array
(
[0] => 1
)
Array
(
[0] => 1
[5] =>
)
up
-4
Anonymous
22 years ago
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:

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