Not a big fan of error suppression here except for throw-away scripts or instances where there really is no good way to catch an error.
Let me explain the behavior of the Uninitialized string offset
error. It's not a bug:
Example #1
$a = 0;
$b = $a['f5'];
$a
is a numeric scalar value. In the second line PHP is implicitly casting this numeric value to a string. The string '0'
has a length of 1.
In PHP you can lookup a character in a string using an array index, as PHP stores strings as arrays internally. For instance:
$s= 'abcd';
print_r($s[1]);
The output of this code will be b
as it is the second character in the string. In example #1 the lookup 'f5'
is being converted to a number as strings can only be indexed by character position. echo intval('f5');
shows us what PHP interprets the 'f5'
string as 0
in a numeric context.
With me so far? Here's what happens when we apply this to example #2
Example #2
$a = '';
$b = $a['f5'];
$a
is zero-length string. The second line is the same as $b= $a[0];
- i.e., the second line is asking for the first character of a zero-length string, but the string contains no characters. So PHP throws the following error, letting you know the index simply does not exist:
Notice: Uninitialized string offset: 0 in C:\websites\tcv3\wc2009\htdocs\aatest_array.php on line 3
These are the hard knocks of programming in a loosely typed language.