WarKirby Posted December 31, 2009 Share Posted December 31, 2009 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 ? Link to comment https://forums.phpfreaks.com/topic/186777-negative-array-indices/ Share on other sites More sharing options...
The Little Guy Posted December 31, 2009 Share Posted December 31, 2009 this might be what you are looking for: prev Link to comment https://forums.phpfreaks.com/topic/186777-negative-array-indices/#findComment-986335 Share on other sites More sharing options...
oni-kun Posted December 31, 2009 Share Posted December 31, 2009 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] Link to comment https://forums.phpfreaks.com/topic/186777-negative-array-indices/#findComment-986336 Share on other sites More sharing options...
gerkintrigg Posted December 31, 2009 Share Posted December 31, 2009 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. Link to comment https://forums.phpfreaks.com/topic/186777-negative-array-indices/#findComment-986383 Share on other sites More sharing options...
salathe Posted December 31, 2009 Share Posted December 31, 2009 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); Link to comment https://forums.phpfreaks.com/topic/186777-negative-array-indices/#findComment-986391 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.