In PHP, what's the fastest and easiest way to get the last position of an Array?
I got this doing $array[ count($array) - 1 ]
, and it works, but is there any simpler and less ugly way?
In PHP, what's the fastest and easiest way to get the last position of an Array?
I got this doing $array[ count($array) - 1 ]
, and it works, but is there any simpler and less ugly way?
You can use the end () .
$ultimo = end($minhaArray);
Another alternative is array_pop()
but this method also removes the last element, I do not know if that's what you need.
If it is an associative array, you need to put the array in the last item and then fetch key()
end($minhaArray);
$ultimaChave= key($minhaArray);
If you want to create a new array with the last element, you can use the array_slice ( ) , this method allows you to create a new array with several elements of the original array, through the second parameter that indicates how many end elements should be passed.
$ultimo = array_slice($minhaArray, -1)
To leave the array in the last element, use the end ()
$arr = array ('maça', 'banana', 'melancia', 'morango', 'uva');
echo end($arr);
output is: uva
The end () function makes the pointer point to the last element of the array, soon if you do:
$array = array('primeiro','segundo','último');
var_dump(current($array));
var_dump(end($array));
var_dump(current($array));
The output will be:
string 'primeiro' (length=8)
string 'último' (length=6)
string 'último' (length=6)
The function current () , returns the current position of the array