2

I'm referring to How to enable notices on my development server

I expect the following code shall give me some warning, when I execute it through, as my $a is not explicitly declared as array

php a.php

<?php

ini_set('display_errors', 1);
error_reporting(E_NOTICE);

$a['key'] = 123;
echo $a['key'] . "\n";   

However, no warning message being printed. Is there anything I had missed?

The PHP I'm using is PHP 5.5.3. I'm not sure this matters?

Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • That's what I didn't ever notice in PHP! That's weird to me as I always initialize my arrays and expected PHP To generate NOTICE for assigning to uninitialized arrays. Good to know, but not a very good habit to use! – Boynux Dec 17 '13 at 03:23

1 Answers1

3

I expect the following code shall give me some warning, when I execute it through, as my $a is not explicitly declared as array

Wrong... by writing $a['key'] = 123; you declare an array and set the key key to the integer number 123. That's a valid PHP array initialization. (The PHP version does not matter in this case.)

To explicitely produce an error notice for testing purposes…

If you want to provoke an error notice for testing purposes, you could add this line:

count($ThisIsNotDefinedOnPurpose);    

which will produce an error notice saying

Notice: Undefined variable: ThisIsNotDefinedOnPurpose in … on line …
e-sushi
  • 13,786
  • 10
  • 38
  • 57
  • 1
    Sadly, this is the case. I'd love for it to generate a notice. – Wrikken Dec 17 '13 at 01:05
  • @Wrikken Just added an example of that to my answer. See *"To explicitely produce an error notice…*" – e-sushi Dec 17 '13 at 01:07
  • Heh, I'm not the OP, I know how to create (and avoid) notices, it just saddens me that `$a['key']='value';` does _not_ create a notice, as it could have saved me some valuable debugging time in the time before I got an editor which highlighted undeclared variables. But thanks nonetheless :) – Wrikken Dec 17 '13 at 01:11
  • @Wrikken I did notice you were not the OP, but I kinda misinterpreted your `I'd love for it to generate a notice.`, thinking you wanted an example of what would produce an error. Anyway, I agree with you that an error would've been logic from a regular coder (C/C++ for example) point of view. Yet, PHP is known for accepting almost anything for initialization and whether we like it or not — from a PHP point of view, that `$a['key'] = 123;` practically is a valid PHP array initialization. Oh well… it's PHP. ;) – e-sushi Dec 17 '13 at 01:16