Why does it work this way?

From: Date: Mon, 02 Apr 2001 16:58:02 +0000
Subject: Why does it work this way?
Groups: php.general 
Request: Send a blank email to php-general+get-46648@lists.php.net to get a copy of this message
-----Original Message----- From: Boget, Chris [mailto:Chris.Boget@wild.net] Sent: Monday, April 02, 2001 11:12 AM To: Mark Roedel Subject: RE: [PHP] Why does it work this way? >> Because "z"+1 turns out to be "aa" (which, if you ask me, >> makes about as much sense as any of the alternatives), > > How is it that "z" + 1 is "aa"? What is PHP using behind the > scenes to get/generate this value? Let me start by correcting myself on a minor technicality. "z"+1 turns out to be 1 (because "z" has an integer value of 0). It's "z"++ that turns out to be "aa". Perhaps one of the core developers who has a better understanding of the behind-the-scenes operations of PHP can elaborate on this, but what it basically points out to me is that "incrementing" and "adding one" aren't always the same thing. I assume this behavior is tied closely to what PHP determines the type of a variable at any given time to be. If we take that as a starting point, then what I see happening is that, for the purposes of incrementing, there are certain ranges defined within PHP. 0-9 is one, obviously. a-z appears to be another. If, for the purposes of the increment operator only, you treat the letters of the alphabet as a range of integers, then the result you're seeing makes perfect sense. You get to your highest digit, then go back to zero and increment the next column. The problem, in the "for" loop that we started out discussing, is that there doesn't seem to be any way to make a comparison that follows those same rules. You can't treat them as integers, because "aa" and "z" have the same integer-value -- zero. Treating them as strings gives the result we've already seen. Other interesting sort-of-related notes: While incrementing works (sort of) on strings, decrementing doesn't appear to have any effect at all. $test="z"; echo $test--; echo $test; results in "zz" Incrementing only appears to work on strings within particular ranges of characters. $test="("; echo $test++; echo $test; results in "((" --- Mark Roedel | "The most overlooked advantage to owning a Systems Programmer | computer is that if they foul up there's no LeTourneau University | law against whacking them around a little." Longview, Texas, USA | -- Owen Porterfield

« previous php.general (#46648) next »