PHP "Tutorials" - Fixing Parse Errors 
PHP Tutorial Index

Fixing Parse Errors

This is the first thing to remember about errors PHP gives you: Keep your sanity.

Do you ever find yourself looking at your code saying "There is NOTHING wrong with this code?! Why is it giving me an error?!"? I usually do and I always find that there is something wrong with my code because the computer doesn't lie.

Something that can take a long time to get the hang of and usually only gets better through constant practice is the reading, understanding, finding and fixing of errors that are thrown at you by the PHP parser when you run a script.

Often, errors will occur when you write larger portions of your script, so although you may be in the zone, try to regularly test your code as you go otherwise you will spend as long looking for small errors as you will spend writing new code.

I will try to cover as many errors as I can here, but my memory is bad so as I remember them I will add them. This page may grow over time.

The second thing you must have before you start chasing errors is an editor that at least tells you the line number.

If you are using Win32, Notepad++ is pretty good. For Linux there is so many editors that suit this it's not funny and if you edit your scripts directly on your webserver cPanel offers a "code editor" that displays line numbers. If yu don't have cPanel for online editing check if your webhost software offers something suitable.

Parse error: syntax error, unexpected X in path/to/file/script.php on line Y
This is probably the most common error you will get. The script will not run because of incorrect syntax somewhere. The trick with this error is that sometimes the problem is not on the line number given, but might be before it:
if ($counter <= 10);
// do something
// do something else

The above code would throw an error like: Parse error: syntax error, unexpected T_ELSE in /path/to/file/script.php on line 5. Line 5 is 'else', but the problem lies on line 1: if ($counter <= 10);
Remove the semi colon from the if() conditional and the problem is fixed.

This is only one example of this type of parse error. 'X' can be a number of things but the main thing to learn is you must read the error message as it gives you clues to what is wrong. In the above example, the clue is that the 'else' is "unexpected". It is not expecting an 'else' because the semi colon is terminating the block of code.

Most of the time, syntax errors are only a small problem. Like a missing or unwanted semi colon, a missing concatenation (full stop) character or a missing or unwanted parenthesis or curly brace. If you find yourself saying "there is nothing wrong with my code" don't fool yourself. There will be some little character missing or that shouldn't be there.

More errors in the future...

PHP Tutorial Index