|
Posted by Richard Lynch on 02/08/05 21:29
Johannes Reichardt wrote:
> Hey there!
>
> i have a routine like this:
>
> $myarray['1'] = 'aösldfjkasöldkjf';
>
> foreach($myarray as $key => $value) {
> echo $key{0}; // outputs nothing
> echo substr($key,0); // outputs 1 like intended
> }
>
> Any ideas why this is like that? I am using
>
> php 4.3.11-dev
At first glance, I though this was a bug as well.
http://us3.php.net/types.string
clearly states that you can access a string's individual characters with
{} much like an array.
So, contrary to what somebody else posted, $key should be '1' and $key{0}
should be '1', if $key is a string, as they posted.
But a bit of investigation turned up this fact:
Even though you used '1' as your index, PHP is forcing it to be an integer.
Add this line in the loop to prove it to yourself:
echo "key type: ", getttype($key), "\n";
This is happening at the construction of the array, as documented at:
http://us3.php.net/manual/en/language.types.array.php
The paragraph after the first two blue boxes of sample code states it
quite clearly:
-------------- excerpt from manual -------------------
If a key is the standard representation of an integer, it will be
interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be
interpreted as "08").
------------------------------------------------------
If this is a real problem in real code, I'd suggest NOT using '1' for
starters, since PHP is gonna make it be 1 anyway when it builds the array.
Then, knowing that your keys are integers, you can act on them
appropriately in your loop to do what you want.
You can convert them to string, or use substr() to let PHP convert them to
string.
I can see how you may think this is bogus behaviour on PHP's part, but
given that HTTP data/keys are always strings and how PHP automatically
builds the hashes for you from incoming GET/POST data, and given that the
integer data from MySQL ends up being a string before PHP sees it, and you
often build indexed arrays out of that, it's a pragmatic approach to
handling the construction of an array.
Hopefully that helps de-mystify what's going on.
It can seem confusing and annoying and downright "wrong" at first that PHP
just silently prefers integer types for indices in arrays, but it has its
benefits as well (see above) and once you get used to it, it's no big
deal, really.
--
Like Music?
http://l-i-e.com/artists.htm
[Back to original message]
|