Jump to content

Negative array indices?


WarKirby

Recommended Posts

Something I'm used to using in another langage is negative indices when referring to array elements, which counts backwards. ie, -1 returns the last element. -2 the second last, etc.

 

Does PHP support this? If not, what's the simplest way to grab the last element of an array ?

 

Nope. -1 and -2 is actually their own array indexes. This can be a simple solution, which is common coding practise:

$secondlast = $arr[count($arr)-1]

I just did it like this:

foreach($array as $key=>$value){
     $last_array_element=$key.': '.$value;
}
echo $last_array_element;

 

It works fine for a few elements, but is certainly not advisable for a lot of them and it's not the cleanest way to do it.

You could also use array_slice/current in such a manner. For example: (Try this code)

 

$array     = array('alpha', 'bravo', 'charlie', 'delta');
$last      = current(array_slice($array, -1, 1));
$next_last = current(array_slice($array, -2, 1));

var_dump($last, $next_last);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.