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 ? Quote Link to comment 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 Quote Link to comment 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] Quote Link to comment 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. Quote Link to comment 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); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.