php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #17065 State explicitly "code $foo['bar'] and not $foo[bar]"
Submitted: 2002-05-07 04:26 UTC Modified: 2002-05-07 05:57 UTC
From: phpbugs at priorwebsites dot com Assigned:
Status: Closed Package: Documentation problem
PHP Version: 4.2.0 OS: Windows XP Home Edition
Private report: No CVE-ID: None
 [2002-05-07 04:26 UTC] phpbugs at priorwebsites dot com
In the "arrays" section "http://www.php.net/manual/en/language.types.array.php", the documentation should state explicitly "code $foo['bar'] and not $foo[bar]".  

It's a small point, but there is already a page and a half of text trying to make this point, without actually stating it. Finally I figured out what makes this part of the documentation unclear; it's because it does not state what it is trying to explain, but just goes right ahead and explains it.

Specifically, I think there are 2 places where the point needs to be made explicitly:

1) 
-----------------------------------------------------
CURRENT TEXT:
Array do's and don'ts
Why is $foo[bar] wrong?
You might have seen the following syntax in old scripts: 
etc.
-----------------------------------------------------
SUGGESTED TEXT
Array do's and don'ts
Use quotes around an associative array index.  For example, code $foo['bar'] and not $foo[bar].  Why is $foo[bar] wrong?
You might have seen the following syntax in old scripts: 
etc.
-----------------------------------------------------


2) 
-----------------------------------------------------
CURRENT TEXT
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
This is wrong, but it works. Then, why is it wrong? The reason is that, as stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this: 

echo $arr[ foo(true) ];
-----------------------------------------------------
SUGGESTED TEXT
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name.  It works, because the undefined constant gets converted to a string of the same name.

As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this: 

echo $arr[ foo(true) ];
 
-----------------------------------------------------


Hugh W Prior

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-05-07 05:57 UTC] sander@php.net
Thanks for excellent tips! I've changed the documentation, the changes should show up on the site in a couple of days.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC