'Warn on undefined array write

Let's preface this with an example of a script with typo:

$bc = getBaseConcept();
$bs['key'] = doOtherStuff($bc['key']);
return $bc;

Obviously in the middle line is a typo. It should be $bc instead of $bs. (And yes this was a legit typo of mine just minutes ago before writing this question)

This did not produce a warning. So my question is: Is there a configuration option that lets this produce a warning?

Specifically: Writing to an array key of a name that was previously undefined.

E_ALL does not seem to help. This should not only generate the warnings for $bar but I want also a warning for $foo.

<?php 
ini_set('error_reporting', E_ALL);
echo ini_get('error_reporting'), "\n";
$foo['bar'] = $bar['foo'];
32767

PHP Warning:  Undefined variable $bar in Standard input code on line 4
PHP Warning:  Trying to access array offset on value of type null in Standard input code on line 4
php


Solution 1:[1]

Unfortunately, php is not like other programming languages. If an unknown variable is used, PHP does the initialisation without complaining. Unfortunately, there is nothing you can do about this.

If you are using an IDE like phpstorm or netbeans the IDE will usually show a hint for uninitisalized variables.

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to false, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

https://www.php.net/manual/en/language.variables.basics.php

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marco