note 39465 deleted from language.types.array by curt
| From: | curt@php.net | Date: | Tue, 06 Jul 2004 02:23:32 +0000 |
| Subject: | note 39465 deleted from language.types.array by curt | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72648@lists.php.net to get a copy of this message | ||
Note Submitter: steffen-staehle@NO.SPAM.gmx.de
----
Noticed some php behaviour concerning array and string type meddling that is likely to confuse you
(at the best) if you are not aware of it. At least it confused me and one of my customers.
Be aware that even though php silently and conveniently converts types for you where applicable,
each variable DOES have a type that defines how the variable behaves and is interpreted.
Consider the following example:
<?
$myvar = 'this is a string'; // makes $myvar be of type string
// now you can access strings array-like,
// $myvar[0] refers to the first character of the string
echo $myvar[0]; // prints 't'
?>
This is fine. You can also use this syntax to modify characters in the string:
<?
$myvar = 'this is a string'; // makes $myvar be of type string
$myvar[0] = 'T';
echo $myvar; // prints 'This is a string'
?>
But don't believe that you can start using the string varaible as a normal array once it has
been typed 'string':
<?
$myvar = 'this is a string'; // makes $myvar be of type string
$myvar['test'] = 'Lets add another array entry.';
echo $myvar['test'];
// you might expect to get 'lets add another array entry'
// but you will get 'L' !
?>
What happens? Instead of discarding the string $myvar and re-creating it as a new array, php
interprets the non-existent index 'test' as 0, assigns the first character of the new
string to the first character of the STRING $myvar. This doesn't even raise the usual (silent)
warning: Undefined index: test
Now this does not seem that dangerous, but if you simply introduce your array varaibles in the way
$myvar[] = 'some value';
$myvar[5] = 'some value';
$myvar['test'] = 'some value';
you risk that IFF $myarray had already been defined as a string for some reason, you will not get at
all what you expect.
In my case, a program was using the variable $lang in that way. Now $lang happens (in some contexts,
depending on the browser, and probably on some php configurations) to be pre-set to the clients
preferred language. Which is a string of the kind 'en'. Imagine what happens... Especially
because the string did exist only occasionally, depending on the CLIENT!
What it boils down to:
ALWAYS initialsie arrays properly:
$myvar = array();
before you start adding items to the array to avoid such problems.
What still strikes me slightly is the silent interpretation of the index ['test'] as [0]
in the string context, here I'd prefer to get a warning of the usual kind.
hope this helps someone
Steffen