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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.