Forum Moderators: coopster
The very act of programming or scripting is defining a set of instructions for a computer to follow, so to me an undefined variable is a glaring instance of unfinished business; the instruction set has encountered a combination of events or conditions that you did not anticipate. If you didn't anticipate it, it's unlikely that the program or script will behave as you want it to - the dumb computer doesn't know what you want.
In many languages, an undefined variable is a fatal error. PHP manages to blunder on as best it can and logs the message so you can fix the problem.
I'll put the question a different way.
Say I want to divide a large array of numbers, any of which might be zero. Should I check every number is zero or just suppress the "division by zero" error message?
Which is best practice? Is one method more efficient than another?
Is that because the maths is harder work than checking if the variable is 0?
Should I apply the same process to undeclared variable notices and either assign an empty value or check if it's set (for instance when using a loop and appending to a variable)?
I like to keep errors to a minimum (to nothing, actually) and use my logs to my advantage.
Also, if you have register globals enabled, having undefined variables can lead to actual hacks in your code. If you are using variables that haven't been initialized or set in your script before you use them then a user, with register globals enabled, can change the value of that variable through various methods. If it is the case that you do have register globals enabled, I would strongly suggest that you disable that feature if you haven't already done so.
Is that because the maths is harder...No, not really. It depends on what your script is trying to accomplish (and zero isn't the same thing as "undefined"). A computer can't divide by zero because humans can't divide by zero because the answer isn't a finite number - it's infinity. That math has different significance than 'some number divided by some other number' and it's up to your script to determine & report what that significance is - if you're using zero to indicate the absence of data then that would be a different thing than a zero which really should be considered part of a set of data.
Should I apply...That depends on the application in your script - in the case of appending, yes, it would be better to start with an empty value.