1

The following

$array = null;
$array['xxx'] = 12;
\var_dump($array);

Will output

array (size=1)
    'xxx' => int 12

Why? Any way to have PHP report these as errors?

7
  • What error are you expecting? Commented Nov 5, 2012 at 13:42
  • This would be the expected output for what you have written. Did you mean to put that back slash before the var_dump? Commented Nov 5, 2012 at 13:43
  • I'm pretty sure that an error reporting set to E_NOTICE would cause a notice to be thrown - I might be wrong though. Edit: I can confirm that this does NOT throw a notice. Even just $foo['bar'] = true; var_dump($foo); seem to work. Commented Nov 5, 2012 at 13:45
  • There's no error with type casting there if that's what you're asking. Commented Nov 5, 2012 at 13:48
  • Check this part of the PHP manual - It's working as designed. If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment. Commented Nov 5, 2012 at 13:50

1 Answer 1

2
$array['xxx'] = 12;

Where $array is null/undefined, the above assignment will create the array and is equivalent to:

$array = array('xxx' => 12);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.