PHP: Using spaces in associative array indices

Nick Heiner picture Nick Heiner · Jan 5, 2010 · Viewed 23.3k times · Source

Is this bad practice/can cause problems?

$_SESSION['stuff to keep']

As opposed to calling str_replace() on the indices.

Answer

Victor Nicollet picture Victor Nicollet · Jan 5, 2010

This is bad practice, but not because of the space.

// file foo.php
$_SESSION['stuff to keep'] = 42;

// file bar.php
if ($_SESSION['stufft o keep'] == 42) frobnicate();

Here, your code is silently misbehaving, and the bug can take a while to be found. Good practice is to use a PHP-enforced name, such as a class constant:

$_SESSION[Stuff::TO_KEEP] = 42;

if($_SESSION[Stuff::TOO_KEEP] == 42) 
// error: no constant TOO_KEEP in class Stuff

You may then define that constant to any constant you find interesting or readable, such as "stuff to keep" (with spaces). Of course, extract() and casting to object won't work anymore, but you shouldn't be doing that anyway with your session.

Allowing user-entered text into session keys is, of course, a blatant security fault.