I have inherited a project from another developer, and it is riddled through and through with the following type of error:
echo $data['example'];
Notice: Undefined index: example
Obviously, I’m going to refactor this to check for the existence of the key prior to the print statement. However, my question is not related to the code per-se.
Is there a version of PHP, or perhaps a setting within PHP whereby echo $data['example'];
would simply return null or 0 in the case of a non-existent key?
I ask because I’m trying to ascertain whether the previous developer had written bad code, or whether their development environment is misconfigured. If it’s the latter, we can obviously resolve these issues for that developer’s future projects.
5
An expression accessing non-existent keys evaluates to null
, much like using variables that weren’t declared or initialized evaluates to null.
These notices, though, are there to let you know your code might not work as expected. Sure, you can hush them up, but really you shouldn’t.
Notices, and warnings should be seen as things to notify you of possible buggy code. Don’t ignore the issue, fix it.
If the development environment truly ignores these notices, as you say, then that is the first problem that needs fixing: set your error level to E_STRICT|E_ALL
when developing, and display the errors.
A notice isn’t fatal, but if you run this code in a production environment, it probably will fill up your logs with clutter, and it does impact performance, too.
All in all: adding an isset
check isn’t too hard. It’s just that it is a bit tedious at times…
1