So you are getting a weird parser error at a line of code that doesn’t have any errors? Here are some tips and tricks I’ve compiled over the 6+ years I’ve been doing PHP scripting for tracing various PHP errors in source code:

1. Start commenting out code near the parser error line number. Start by commenting out lines of code in and around the parser error. Execute the code after each section of comment. For example, let’s say the error is at line 300, then comment out code from 295 to 300, and then re-run the script. Still getting an error? then try commenting out 300-305. The parser doesn’t always tell you the exact line of code where an error appears.

2. Watch for parser errors at the End of Feed (EOF). If the parser error line number is the very bottom of your script then you likely have a braces mismatch. These can be very difficult to spot if you’ve added a bunch of code without running the program. Here’s an example of a braces mismatch:

<?php
$flag = 0;
$names = array(‘TDavid’,‘php-scripts.com’,);
foreach($names as $each) {
if($each == ‘TDavid’) {
$flag = 1;
if($flag == 1) {
print ‘I found TDavid’;
}
}
?>

Can you spot the brace mismatch above? It should be directly below the $flag=1; One way in coding that you can cut down on brace mismatches is always indent. Let’s rewrite the code above with indenting below:

<?php
$flag = 0;
$names = array(‘TDavid’,‘php-scripts.com’,);
foreach($names as $each) {
     if($each == ‘TDavid’) {
        $flag = 1;
     }
     if($flag == 1) {
         print ‘I found TDavid’;
     }
}
?>

Notice how the braces match up? If you indent your code you’ll keep braces closed. There are also some helper text editor programs that will watch for brace mismatches and alert you to this common error.

3. Do not assume anything. If you didn’t have an error with a section of code before, doesn’t mean you didn’t accidentally hit the keyboard in the source code somewhere and add some bogus character. I’ve done this before and it can be maddening. Solution: if you work in revisions, you can go back to a prior version that was running before your changes and rebuild into the changes you made.

4. Watch for concatenation errors. Concatenation errors can be quite common but can be tricky to spot. See the buggy code below:

<?php
$address = ‘123 ‘ . str_replace(“|”,” “,$address) . “<br />\n $city . “$state, $zipcode”;
?>

See the error above? I’ve learned for longer concatenation that the code can be easier to read by breaking up the concat code on muliple lines like this:

<?php
$address = ‘123 ‘ . str_replace(“|”,” “,$address)
            . “<br />\n . $city
            . “$state, $zipcode”;
?>

Notice how there is no more than two concat statements on each line, keeping the code from scrolling in the text editor window. The scroll can make it harder to spot errors.