5

I was hit by a bug where a returned DB result was expected to be an array but due to a glitch in the SQL query in one instance the DB wrapper correctly returned null. Unfortunately the code did not expect that (=bug).

However, I was surprised to see PHP did not issue a warning when the null value was accessed as an array. Does anyone know if it's by design or there is an explanation I'm missing?

Example to show what I mean:

$ php -a
Interactive shell

> echo phpversion() . PHP_EOL;
5.4.26

php > echo $test['value'];
PHP Notice:  Undefined variable: test in php shell code on line 1

php > $test = 'string';
php > echo $test['value'];
PHP Warning:  Illegal string offset 'value' in php shell code on line 1

php > $test = null;
php > echo $test['value'];

I would expect the last statement to generate a warning.

Nils
  • 189
  • 1
  • 14
  • I don't see how a warning would help you there. Simple sanity check (is_array and isset($yourarray['key']) would suffice there. – N.B. May 07 '14 at 11:03
  • Yes, a sanity check is the solution, but the query in this instance was always expected to return a result ('SHOW STATUS LIKE' query where it was already verified table was existing) or throw an exception upon error, so a warning would have helped me. As @deceze mentions this q is a duplicate (which my own searching did not find) and the answer is at http://stackoverflow.com/a/10990864/957040 Despite accepting the stance that "automatic conversion to array is currently undefined" in PHP I would still like to see a warning. – Nils May 07 '14 at 12:06
  • I suspect this is because PHP has a tradition of (usually) pretending `NULL` is the same as an empty array (i.e. `array()`). However, this is also known to happen for some other scalar values :/ – Andrea Feb 03 '15 at 00:56

0 Answers0