2009/09/08

undefined index

$foo = array();

$foo[bar] = 'bad'; //this works but produce undefined index notice.

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 PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

-- by http://www.nusphere.com/kb/phpmanual/language.types.array.htm

//So always do:
$foo['bar'] = 'good';
//or
$bar = "bar";
$foo[$bar] = 'good';


There is another case may cause undefined index notice.

$bar = 'myindex';
if (!is_array($foo[$bar])){
   // do something;
}


Because $foo[$bar] is not defined yet, it could not be evaluated by in_array. The correct way is that

$bar = 'myindex';
if (isset($foo[$bar]) &&
!is_array($foo[$bar]) ){
   // do something;
}

No comments:

Post a Comment