Re: what to use instead of foreach

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Mark Kelly wrote:
> Hi Phil.
>
> On Monday 13 April 2009, PJ wrote:
>   
>> Thanks for the suggestion, Mark. I've already experimented with count;
>> you're close, but there is still a small glitch and that's in count();
>> foreach doesn't give a damn about count so you can't use that - it is
>> reset once inside the foreach loop.
>>     
>
> Look again at the code - the count() is not inside the foreach, so it is 
> not reset, simply stored in $lastIndex for comparison.
>
> If your array is associative then simply use another variable to find the 
> last value in the array - the code doesn't need to change much.
>
> Try actually running the code below - it does work, as does the previous 
> version I posted if the array is not associative. 
>
> I'd prefer it if in future you didn't tell me that my code didn't work 
> without actually trying it - I tested that snippet before posting it, as I 
> did with the following.
>   
My apologies. It certainly was not meant to disparage the suggestion. I
had tried all sorts of counts as I mentioned before. I spend an awful
lot of time testing and trying but I'm afraid I don't really grasp all
the concepts involved. I am rather visually oriented and not seeing
things is rather frustrating.
I shouldn't assume so much and will certainly examine your suggestion
and learn where I went wrong.
Thanks again.
Phil
> HTH
>
> Mark
>
> <?php
> // Non-associative array (the code I posted previously).
> $a = array('1','2','3');
>
> $lastIndex = count($a) - 1;
> $outputString = '';
> foreach ($a as $index => $value) {
> 	if ($index != $lastIndex) {
> 		$outputString .= "$value, ";
>     } else {
>         $outputString = rtrim($outputString,', '); // Strip last comma.
>         $outputString .= " & $value<br />";
>     }
> }
> echo $outputString;
>
> // Associative array (changed only very slightly).
> $a = array('martha' => '1','jock' => '2','dave' => '3');
>
> $lastIndex = count($a);
> $counter = 0;
> $outputString = '';
> foreach ($a as $index => $value) {
> 	$counter++;
> 	if ($counter != $lastIndex) {
> 		$outputString .= "$value, ";
> 	} else {
> 		$outputString = rtrim($outputString,', '); // Strip last comma.
> 		$outputString .= " & $value<br />";
> 	}
> }
> echo $outputString;
> ?>
>
>   


-- 
unheralded genius: "A clean desk is the sign of a dull mind. "
-------------------------------------------------------------
Phil Jourdan --- pj@xxxxxxxxxxxxx
   http://www.ptahhotep.com
   http://www.chiccantine.com/andypantry.php


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux