After writing some PHP code, I encountered this weird error that displayed this message: “Parse error: syntax error, unexpected $end” on the page and did not execute any other code.
It appears that there are multiple causes for this error, and is a syntax error – that is, missing some code or writing the code differently from how the compiler expects it to be.
Below are the common causes (the problem I had is listed first) and how to fix them:
Missing or unmatched parantheses
If you have not learnt a C-style language before, PHP is rather confusing with all its braces {} and parantheses (), which are often used to nest code, seperate code and for various iteration elements etc.
In my case, the error was caused by a space between if and parenthesis when I wrote a PHP function definition. The code was something like below:
<?php if (get_theme_mod('footerwidget') == 'Yes' { ?>
As you can see, I have two opening parentheses ‘(‘ but only one closing parenthesis ‘)’, leaving the code incomplete and causing the error. Fixing the error can be done by ensuring that all the open parantheses are matched by closing ones.
Missing or unmatched braces
Similar to the above case, missing braces {} can cause the error. Braces find use in PHP very often, and it is not unusual to write code nested several layers deep, each marked by braces. It can get confusing in such cases.
A handy tip for both missing braces and parentheses would be to write the opening and closing braces or parantheses first, like {}, and then go back between the braces and start writing your code. That way, you would not forget to close the brace.
Short hand PHP tags on unsupported systems
A variation of this error is “Parse error: syntax error, unexpected $end in X on line Y”.
This is usually encountered if you use the PHP quick tags (<? ?>) in code, but the server does not support them (disabled in PHP.ini file). To fix this, you can either change all quick tags to regular tags <?php ?> (recommended), or enable the short hand in php.ini file (which is not recommended for security reasons, and also depreciated).