purencool Posted May 29, 2011 Share Posted May 29, 2011 hi phpfreaks, I want change the last value when iterating through an array but I can't seem to get to work. I can never get to the echo housing but can't work out why any advice would be great. foreach ($headings as $key => $cValues){ $cols .= $key.","; if(current($headings)== count($headings)){ echo "housing"; $cols .= $key; break; } } Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/ Share on other sites More sharing options...
requinix Posted May 29, 2011 Share Posted May 29, 2011 current() returns the value, not the key. If $headings is a normal array (not an associative array) then you need to compare count() with the key. Also, if the count is N then the key will always be between 0 and N-1. So that will never match either. However you don't need a loop in the first place. $cols = implode(",", array_keys($headings)); Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/#findComment-1222025 Share on other sites More sharing options...
purencool Posted May 29, 2011 Author Share Posted May 29, 2011 lol how stupid!!!!!!!!!!!!! what was I thinking!!!!!!!!!!!!! thanks for the help Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/#findComment-1222034 Share on other sites More sharing options...
xyph Posted May 29, 2011 Share Posted May 29, 2011 <?php $headings = array( 'test'=>'one', 'blahblah'=>'two', 'lastone'=>'three' ); end($headings); $lastKey = key( $headings ); foreach ($headings as $key => $cValues){ if($key == $lastKey){ echo $cValues; } } ?> requinix probably has the _better_ answer though. Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/#findComment-1222035 Share on other sites More sharing options...
purencool Posted May 29, 2011 Author Share Posted May 29, 2011 thanks for your input Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/#findComment-1222046 Share on other sites More sharing options...
.josh Posted May 29, 2011 Share Posted May 29, 2011 I know it's not the total of what you are doing, but FYI you can also use array_pop to remove the last element of the array, and array_push to add something new to the end. Quote Link to comment https://forums.phpfreaks.com/topic/237809-get-an-end-of-the-array/#findComment-1222055 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.