[nycphp-talk] string function
Michael Southwell
michael.southwell at nyphp.com
Thu Jul 3 14:52:29 EDT 2008
Brian O'Connor wrote:
> >> $p = explode('|',$y);
> >> for($i=0,$c = count($p);$i<$c;) {
> >> echo $p[$i++],' ', $p[$i++], "<br>\n";
> >> }
> >
> > I believe this will miss the first element of $p; you need instead:
> >
> > for ( $i = -1, $c = count( $p ); $i < $c; ) {
>
> If you start from -1, then you would need to use ++$i rather than $i++
>
> Starting from -1 and using ++$i would be faster than what I wrote.
>
>
> Starting at -1 to avoid using ++$i seems way more confusing than
> starting at 0 and using $i++. As someone mentioned above, confusing
> code will offset any computation savings you gain.
And in the interest of being as clear as possible here, and not to
mislead any lurkers or anybody who can be as dumb as I can:
I was wrong when I said "this will miss the first element." The reason
is that echo $p[$i++] first echoes $p[$i] and only then increments $i;
it does *not* echo element $i++ as I must have been thinking (out of
stupidity or inattention or whatever) when I wrote that.
--
=================
Michael Southwell
Vice President, Education
NYPHP TRAINING: http://nyphp.com/Training/Indepth
More information about the talk
mailing list