Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP doesn't throw "undefined offset" notice anymore?

Tags:

php

I'm running PHP 5.5 and and unable to have it throw undefined offset notice anymore.

$ php -a
Interactive mode enabled

php > error_reporting(E_ALL);
php > $b = null;
php > var_dump($b['foo']);
NULL
php > $b = "string";
php > var_dump($b['foo']);
PHP Warning:  Illegal string offset 'foo' in php shell code on line 1
string(1) "s"
php > $b = 345678;
php > var_dump($b['foo']);
NULL

Am I doing something wrong or the undefined offset notice has been abolished for most data types?

like image 907
tacone Avatar asked Sep 26 '14 12:09

tacone


2 Answers

Using the following does throw the notice in all PHP versions:

$b = array();
var_dump($b['foo']); 

All other variations don't usually give a notice: http://3v4l.org/18qM5

like image 112
Jim Avatar answered Nov 17 '22 11:11

Jim


I can't give you the exact explanation why you can access a 'NULL' value like an array, but since PHP 5.X it is possible to get the X'th character of a string using the square brackets.

Take a look at the following example:

$string = "testing this stringy thingy";

$character = $string[0]; 
echo $character; //returns 't'

$character = $string[21];
echo $character; //returns 'h'

I think this has something to do with accessing 'NULL' using the square brackets... Maybe someone else can help out with a better answer :)

Update

When setting the variable as 'NULL', PHP holds it in memory but it isn't used for anything. After setting the variable using the square brackets, the variable turns into an array and can now be accessed as one (like we expect when something is an array).

$string = null;
$string['abc'] = 123;

print_R($string); //Array ( [abc] => 123 )

echo gettype($string); //outputs "array". 

var_dump(isset($string['abc'])); //returns "true"

So, why is PHP not throwing an 'E_NOTICE'error: Because the variable is automatically casted to an Array.

like image 36
Benz Avatar answered Nov 17 '22 09:11

Benz