Re: what to use instead of foreach

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

 



Mark Kelly wrote:
> Hi.
>
> On Sunday 12 April 2009, PJ wrote:
>   
>> foreach does not allow for different formatting for output...
>>     
>
> [snip]
>
>   
>> But how do you get result1, result2 & result3 // with <br> at end ?
>>     
>
> $lastIndex = count($a) - 1; // Adjust for zero-indexing.
> $outputString = '';
> foreach ($a as $index => $value) {
>     if ($index != $lastIndex) {
>         $outputString .= "$value, ";
>     } else {
>         $outputString = rtrim($outputString,', '); // Strip last comma.
>         $outputString .= " & $value<br />";
>     }
> }
> echo $outputString;
>
> Like that? If your array is associative you can drop the $lastIndex calc 
> and adjust the loop to update a counter instead. 
>
> HTH
>
> Mark
>
>   
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. And, the "as $index" cannot relate
to the $lastIndex because the array index (which would be the index in
the "as $index") can be any number and is not sequential. There are a
couple of other ways, one is suggested by Jim Lucas in the thread
"extract varying data from array with different formatting"; another is
to change the SELECT query to use a ranking reference - I think it may
be a bit more complex, though.
Any other thoughts? ;-)  I'll appreciate them.

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