Last array element

Syntax of command to get the last element of the array depends on the programming language. One might expect it to be simple in every programming language, though. So then why do we have 10 different solutions for PHP and 13 different options for JavaScript?

What should be the pragmatic way of solving this puzzle (assuming that the array is not empty)?

// In JavaScript
const item = arr[arr.length - 1];
// In PHP
$item = $arr[array_key_last($arr)];

Function array_key_last() gives the last key in the array, and we access the array element by the key $arr[array_key_last($arr)]. The only thing worth mentioning here is that the array_key_last() was added in the version 7.3.0 , which is the oldest supported version at the moment of writing.

Last updated