Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Why when you are adding value to array with not existing index it doesnt raise NOTICE?

Tags:

arrays

php

For example:

$array = [];

echo $array['bar']; // PHP NOTICE - trying to access not existing key`

$array['bar'][] = 'foo'; // Nothing

I understand that it creates array with that index 'bar', but how does PHP deals with that internally?

like image 476
povils Avatar asked Dec 12 '16 16:12

povils


1 Answers

$array['bar'][] = 'foo'; doesn't return a notice or error because there is no error. You are creating a new array index, and another index within that, and assigning a value to it. That's what the statement means. There's no error to return.

If you want to have behaviour for if a particular array index is not set, you can use array_key_exists (http://php.net/manual/en/function.array-key-exists.php):

if(array_key_exists('bar', $array)){
    $array['bar'][] = 'foo';
} else {
    // something else
}

That's if this question is functional (ie., you're trying to accomplish something specific). If the question is more conceptual - why doesn't PHP read the variable assignment as an error:

PHP is capable of initializing and assigning a variable in one line, ie $foo = 'bar'. This does not return an error even though $foo was not previously defined because PHP initializes the variable first. The same method holds true for array indexes. $array['foo'][] = 'bar' doesn't return an error or a notice because PHP is initializing the array index just as it would a variable.

like image 119
CGriffin Avatar answered Oct 21 '22 08:10

CGriffin