NYCPHP Meetup

NYPHP.org

[nycphp-talk] Syntax question (was handling forms (relative newbie))

Hans Zaunere hans at nyphp.org
Mon Oct 6 16:17:19 EDT 2003



Aaron Fischer wrote:

> Quick question:  I noticed on some posts to my original question the 
> syntax for accessing an array element of $_POST or $_SESSION uses single 
> quotes around the array element.  In the reference book I am using there 
> are no quotes, just something like $_SESSION[first_name].  I googled a 
> number of discussions and articles and have found examples of both methods.
> 
> So, my question is, does it matter if one uses the single quotes or no 
> quotes as both seem to work?  Are there any security issues or other 
> nuances I should be aware of or is the language just forgiving in this 
> respect and I could choose either way?

It matters; unfortunately PHP lets people be too sloppy in this respect.

Doing:

$anarray[elementname];

assumes elementname as a constant first; since it's not a constant first, it takes it literally as a string.  This is *very* bad (performance/security/style) and any book that gives examples like this should have it's worth reconsidered.

You should always do:  $anarray['elementname'];  unless you need to get fancy, as in the following examples:

define('ELEMENTNUM', 5);
$anarray[ELEMENTNUM];         // This is totally different from the very first example.


$elementname = 'somethingelse';
$anarray[$elementname];       // This is the same as writing  $anarray['somethingelse'];


$elementname = 'elementnum';
$anarray["{$elementname}5"];   // This could also be written  $anarray[$elementname.'5'];


So yeah, don't ever do $_SESSION[first_name];  PHP is loosely typed and forgiving - but don't take advantage of it too much, as it'll come around and burn you some time :)

H





More information about the talk mailing list