Reading the PHP documentation has convinced me (again) of what a mind-bogglingly broken language this is. Quickly, see if you can predict this behavior:

<cr:code lang=“php”>

"The element indexed by '8'", "foo" => "The element indexed by 'foo'", "010" => "The element indexed by '010'" ); // The string index "8" clobbered the integer index 8. // But the string index "010" didn't... echo "Now check out what PHP thinks the array is..."; print_r ($things); echo "\n\n"; // As expected echo "\$things[0]: $things[0]\n"; echo "\$things[1]: $things[1]\n"; // Okay, so strings are interpreted as integers sometimes... echo "\$things[\"0\"]: " . $things["0"] . "\n"; // Ah, now things become strange. This integer key gets the string "8" instead. echo "\$things[8]: $things[8]\n"; // This should refer to the 8th element, but it gets converted to an integer by // the preprocessor, then to a string, where it matches the clobbered 8th // element... echo "\$things[010]: " . $things[010] . "\n"; // This string key returns the expected "8" element... echo "\$things[\"8\"]: " . $things["8"] . "\n"; // But this string octal key gets the "010" key as expected. Note that it // *doesn't* get the integer 8, as you might expect from $things["0"] echo "\$things[\"010\"]: " . $things["010"] . "\n"; echo "\n"; ?>

Here’s the output (PHP 5.2.6-3ubuntu4.1):

cr:code This is the integer literal octal 010: 8

Now check out what PHP thinks the array is…Array ( [0] => The 0th element [1] => The 1st element [2] => The 2nd element [3] => The 3rd element [4] => The 4th element [5] => The 5th element [6] => The 6th element [7] => The 7th element [8] => The element indexed by ‘8’ [foo] => The element indexed by ‘foo’ [010] => The element indexed by ‘010’ )

$things[0]: The 0th element $things[1]: The 1st element $things[“0”]: The 0th element $things[8]: The element indexed by ‘8’ $things[010]: The element indexed by ‘8’ $things[“8”]: The element indexed by ‘8’ $things[“010”]: The element indexed by ‘010’ </cr:code>

This is an excellent example of why grafting features onto your language piecemeal to satisfy users who can’t be bothered to figure out whether they are working with strings or integers is a Bad Idea™.

Aziz
Aziz on

good example

Post a Comment

Comments are moderated. Links have nofollow. Seriously, spammers, give it a rest.

Please avoid writing anything here unless you're a computer. This is also a trap:

Supports Github-flavored Markdown, including [links](http://foo.com/), *emphasis*, _underline_, `code`, and > blockquotes. Use ```clj on its own line to start an (e.g.) Clojure code block, and ``` to end the block.