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.
1 Answer 1
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...
-
Yep, looks like you will need to isset() or !empty() all your output from this inherited code before moving on. Especially if $data is of a custom class that implements ArrayAccess and sets a Notice instead of an exception.Tyson of the Northwest– Tyson of the Northwest2014年08月15日 22:58:31 +00:00Commented Aug 15, 2014 at 22:58
null
, and ignoring notices is about as bad an advice as it gets. If your code is riddled with notices like this, advising to silence them is like suggesting to a hoarder to cram all his stuff under the carpet. It doesn't solve the problem.