Jump to content

get an end of the array.


purencool

Recommended Posts

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;
					}
				}

 

Link to comment
Share on other sites

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));

Link to comment
Share on other sites

<?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.

Link to comment
Share on other sites

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.