I am new to PHP. When I use “echo” to print an array element, my success seems to depend on what I name the index. That can’t be right, right?! I feel like I am going crazy. This code:
$ARRAY['q1'] = 'foo';
echo "q1 is $ARRAY[q1]<br>";
Works fine. But this code:
$ARRAY['1q'] = 'foo';
echo "1q is $ARRAY[1q]<br>";
Produces the error:
Parse error: syntax error, unexpected T_STRING, expecting ‘]’ in /var/www/html/test.php on line 6
I know that I can correct the problem like this:
echo "1q is " . $ARRAY['1q'] . "<br>";
But my question is WHY would the array index “1q” vs. “q1” matter in the first code block? I even checked to see if 1q is a constant of some kind but it doesn’t seem to be. Is this an improper way to insert an array element in a string? (I copied it from the PHP documentation.)
This is in PHP 5.3.8. I really appreciate any help.
EDIT:
Ok I got this echo syntax from Example #8 on this page of the PHP manual: http://www.php.net/manual/en/language.types.string.php Apparently it is not the right way to do things. I will add a user-contributed note to the manual.
An entire script that produces this error would be:
<?php
$ARRAY['1q'] = 'foo';
echo "1q is $ARRAY[1q]<br>";
?>
When using arrays in a double-quoted string, if PHP sees the array key start with a number, it assumes the entire key is a numeric index, e.g.
is interpreted as
$arr[123]. Theabcportion is what’s producing the expected string error, since a numeric key can’t contain non-numeric components.To fix this, you’ll have to use
with properly quoted array indexes