Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PHP not complain when I treat a null value as an array like this?

Tags:

arrays

php

null

In PHP, I have error_reporting set to report everything including notices.

Why does the following not throw any notices, errors or anything else?

$myarray = null; $myvalue = $myarray['banana']; 

Troubleshooting steps:

$myarray = array(); $myvalue = $myarray['banana']; // throws a notice, as expected ✔  $myarray = (array)null; $myvalue = $myarray['banana']; // throws a notice, as expected ✔  $myarray = null; $myvalue = $myarray['banana']; // no notice or warning thrown, $myvalue is now NULL. ✘ Why? 

It's possible it's a bug in PHP, or I'm just not understanding something about how this works.

like image 678
thomasrutter Avatar asked Jun 12 '12 03:06

thomasrutter


People also ask

Can an array be null PHP?

An array cannot be null.

Does PHP support null?

PHP NULL ValueNull is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Does null return false PHP?

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0 , "0" , "" , and false . Show activity on this post. Null is nothing, False is a bit, and 0 is (probably) 32 bits.

Is there any operator in PHP which validates variable for null value?

You can use comparison operator == , === or != to check whether a variable is null or not.


1 Answers

There are three types which it might be valid to use the array derefence syntax on:

  • Arrays
  • Strings (to access the character at the given position)
  • Object (objects implementing the ArrayAccess interface)

For all other types, PHP just returns the undefined variable.

Array dereference is handled by the FETCH_DIM_R opcode, which uses zend_fetch_dimension_address_read() to fetch the element.

As you can see, there is a special case for NULLs, and a default case, both returning the undefined variable.

like image 94
stackfu Avatar answered Sep 28 '22 11:09

stackfu