简体   繁体   中英

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

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.

It's an implicit form of type casting . So when we do this

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

It's equivalent to

$array['bar'] = (array)'foo';

PHP (for better or worse) automatically makes the array for you. Therefore, there's no errors to report. Interestingly, PHP doesn't like you doing this

$array = ['Foo' => 1];
$array['Foo'][] = 2; // Warning: Cannot use a scalar value as an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM