2
<?php
  ini_set('display_errors',1);
  ini_set('error_reporting',-1);
  $data = null;
  var_export( $data['name']);
  echo PHP_EOL;
  var_dump($data['name']);

Why the result is null, but no notice or warning occured?

light
  • 51
  • 2
  • I haven't found anything in the documentation that explains the lack of an error for an undefined array index. Looks like [this PHP bug](https://bugs.php.net/bug.php?id=68110) might be related? – Matt Gibson Jan 10 '15 at 17:16
  • 2
    possible duplicate of [Why does PHP not complain when I treat a null value as an array like this?](http://stackoverflow.com/questions/10990321/why-does-php-not-complain-when-i-treat-a-null-value-as-an-array-like-this) – mleko Jan 10 '15 at 17:19

3 Answers3

0

Because null is an undefined type, $data['name'] therefore creates its own array.

0

If you check the data type of $data before assigning null, you will get the undefined variable notice.

echo gettype($data);
$data = null;

After you assigned null to $data, you will see NULL for its value and its data type.

$data = null;
echo gettype($data);
var_dump($data);

According to the documentation of NULL, you're getting NULL for $data['name'] means that it has not been set to any value yet.

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

A variable is considered to be null if:

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().

The following two examples show that the previously defined variable is not auto-converting to array, and keep its original data type.

Example 1:

$data = null;          // $data is null
var_dump($data['name']); // null
var_dump($data[0]);    // null

Example 2:

$data = 'far';  // $data is string
$data[0] = 'b'; // $data is still string
echo $data;     // bar
Sithu
  • 4,752
  • 9
  • 64
  • 110
-1

Just reread documentation about type casting in php.

http://php.net/manual/en/language.types.type-juggling.php

PHP is not so strict as c/c++ or java :-)

Alex
  • 16,739
  • 1
  • 28
  • 51