Re: When is "z" != "z" ?

From: Date: Tue, 06 Jun 2006 17:44:23 +0000
Subject: Re: When is "z" != "z" ?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-237473@lists.php.net to get a copy of this message
At 10:38 AM 6/4/2006, tedd wrote:
for ($i="a"; $i<"z"; $i++) { echo($i); } -- it stops at "y" But, if you use -- for ($i="a"; $i<="z"; $i++) { echo($i); } -- it prints considerably more characters after "z" than what one would normally expect -- why is that?
Tedd, The discussion of PHP strings has been interesting; thanks for sparking that. Of course, your subject line to the contrary, it's not that "z" != "z", it's that storing an alphabetic character assumed to be a single byte in a variable and then incrementing it can result in a two-byte result. I find it plausible that the statement $a = "a" produces a two-byte result in the first place, we just don't notice it because the second byte is turned sideways and is very, very skinny. I assume you know (but I'll state it anyway for the record) that to avoid the problems you've encountered by trying to treat apparently multi-byte PHP string variables like one-byte numerics, you can simply use numerics themselves:
        for ($i = ord("a"); $i <= ord("z"); $i++)
        {
                echo chr($i);
        }
ord() and chr() being the PHP functions to yield the numeric value of a character and the ASCII character of a numeric value: http://php.net/ord & http://php.net/chr To save that hard-working server a few machine cycles, one would presumably store ord("z") in a variable before the loop began and test for that each iteration. Warm regards, Paul

« previous php.general (#237473) next »