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?
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With