7
In PHP, what is the fastest and easiest way to get the last position of an Array?
I got it by doing $array[ count($array) - 1 ]
, and it works, but there’s some way simpler and less ugly?
7
In PHP, what is the fastest and easiest way to get the last position of an Array?
I got it by doing $array[ count($array) - 1 ]
, and it works, but there’s some way simpler and less ugly?
15
You can use the end().
$ultimo = end($minhaArray);
Another alternative is the array_pop()
but this method also removes the last element, I do not know if it is what you need.
If it is an associative array you need to put the array in the last item and then fetch the key()
end($minhaArray);
$ultimaChave= key($minhaArray);
If you want to create a new array with the last element, you can use array_slice(), this method allows creating a new array with several elements of the original array, through the second parameter indicating how many end elements should be passed.
$ultimo = array_slice($minhaArray, -1)
6
To leave the array in the last element use the function end()
$arr = array ('maça', 'banana', 'melancia', 'morango', 'uva');
echo end($arr);
the exit is : uva
Why the negative vote? +1
5
The function end(), makes the pointer point to the last element of the array, so if you do:
$array = array('primeiro','segundo','último');
var_dump(current($array));
var_dump(end($array));
var_dump(current($array));
the exit will be:
string 'primeiro' (length=8)
string 'último' (length=6)
string 'último' (length=6)
The function Current(), returns the current position of the array
Browser other questions tagged php array
You are not signed in. Login or sign up in order to post.
Who voted negative can also leave explanation if found some inaccuracy.
– Sergio
Thanks! That’s just what I needed!
– Xavier Sam