Use php NULL as array

<?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 is the result null but there was no notification or warning?

+3


source to share


3 answers


Since null is undefined, $data['name']

so it creates its own array.



0


source


If you check the datatype $data

before assigning null

you will get an undefined variable notification.

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

      

Once you have 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 NULL documentation , you get null

for $data['name']

means that it hasn't been set to any value yet.

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

A variable is considered null if:

  • it is assigned the constant NULL.

  • no value has been set yet.

  • it has been canceled ().



The next two examples show that the previously defined variable was not automatically converted to an array and retained 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

      

0


source


Just re-read the documentation about type casting in php.

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

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

-1


source







All Articles