I checked my project wide error logs today and found a plethora of these notices:
"Undefined index: myVar in /myScript.php on line 3"
It took me ages to find the error. So here it is, condensed down to just 4 lines of code (originally it was a little bit more than that). I just did not see the semicolon!
if (isset($_POST['myVar']));
{
echo $_POST['myVar'];
}
In other cases where things are prone to errors I have my ways. Like in this example where I falsly use "=" instead of "==":
if ($myVar = 5) {} // valid PHP but sooo wrong...
if (5 = $myVar) {} // parser error warns me of my own mistakes
So what could I have done better in above example to not let the semicolon thing happen?
You can improve your coding style.
The PSR-2 style does not allow putting the curly braces on a new line when using IF, they have to be on the same line as IF, separated with a space.
if (isset($_POST['myVar'])); {
echo $_POST['myVar'];
}
And this looks a little bit more suspicious than your code. Still enough characters to confuse the searching eye, but you usually do not expect a semicolon between parentheses and curly braces of an IF statement.
Coding style is all about making errors look like errors and stand out prominently. While this one really is valid syntax, it would look strange enough to spot the error, because semicolons belong at the end of a line.
If you'd format your code automatically, you'd get your original code back, making you wonder why the curly brace went to the next line...
To answer your direct question, this is a matter of either using an IDE that gives you better hints, or simply debugging better so it doesn't take you ages. You could also turn on error messages so you get an immediate error rather than having to check logs.
error_reporting(E_ALL);
Then use the error message hint to help isolate the problem. It said the error was on line 3 and that myVar
was undefined, so you should really focus on line 3 or what is immediately before it and be looking as to why an undefined variable is being used.
I'm guessing after this situation, you'll notice the semi colon quicker.