tacone
tacone

Reputation: 11451

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

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?

Upvotes: 12

Views: 471

Answers (2)

Benz
Benz

Reputation: 2335

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.

Upvotes: 2

Jim
Jim

Reputation: 22656

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

Upvotes: 2

Related Questions