debugging parsing php syntax-error

PHP parse/syntax errors; and how to solve them


Everyone runs into syntax errors. Even experienced programmers make typos. For newcomers, it’s just part of the learning process. However, it’s often easy to interpret error messages such as:

PHP Parse error: syntax error, unexpected ‘{‘ in index.php on line 20

The unexpected symbol isn’t always the real culprit. But the line number gives a rough idea of where to start looking.

Always look at the code context. The syntax mistake often hides in the mentioned or in previous code lines. Compare your code against syntax examples from the manual.

While not every case matches the other. Yet there are some general steps to solve syntax mistakes.
This references summarized the common pitfalls:

Closely related references:


While Stack Overflow is also welcoming rookie coders, it’s mostly targetted at professional programming questions.

  • Answering everyone’s coding mistakes and narrow typos is considered mostly off-topic.
  • So please take the time to follow the basic steps, before posting syntax fixing requests.
  • If you still have to, please show your own solving initiative, attempted fixes, and your thought process on what looks or might be wrong.

If your browser displays error messages such as “SyntaxError: illegal character”, then it’s not actually -related, but a syntax error.

Syntax errors raised on vendor code: Finally, consider that if the syntax error was not raised by editing your codebase, but after an external vendor package install or upgrade, it could be due to PHP version incompatibility, so check the vendor’s requirements against your platform setup.


  • 2

    This isn’t enough data to be an answer, but one could write a analyser with parsekit_compile_string, and put more friendly answers on it. If integrated into your IDE, this could be quite informative.

    Aug 12, 2013 at 21:49

  • 7

    You put an impressive amount of work into this. Respect for that. It’s probably very good for teachers to learn to fast point out errors or for those creating IDEs or implementing quick fixes. However, IDEs will already effectively do most of this work for you, as @Panique suggests. Additionally, im many cases the start again from scratch is a good option.

    – allprog

    Aug 15, 2013 at 12:34

  • 2

    @Fred-ii- I think most causes are similar to the T_IF / T_FOREACH / ... block. Albeit I wanted to compile a more custom summary for IF/ELSE/ELSEIF questions.

    – mario

    May 28, 2016 at 13:45

  • 3

    You know, I wish I had had this list when I was learning PHP years ago.Very helpful, especially for beginners.

    – user10957435

    Feb 26, 2019 at 20:01

  • 2

    @β.εηοιτ.βε Great idea; there’ve been quite a handful of these questions recently. Though it would need to cover the three common cases (import scope, traits, closures) if possible.

    – mario

    Aug 22, 2019 at 14:16


What are the syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can’t guess your coding intentions.

Function definition syntax abstract

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an IDE or editor for PHP with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    Expected: semicolon

  • Read the language reference and examples in the manual.
    Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected T_STRING, expecting ; in file.php on line 217

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake, however.

It’s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators, this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing ; semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. should be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone if it’s not ++, --, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

  • Whitespace is your friend.
    Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretize the line number for parsing errors. Instead of looking at the very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. The code you can easily identify as correct,
      2. The parts you’re unsure about,
      3. And the lines which the parser complains about.

      Partitioning up long code blocks really helps to locate the origin of syntax errors.

  • Comment out offending code.

    • If you can’t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can’t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.

    • PHP’s alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements/lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for the string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don’t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but other crops up in some code below, you’re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can’t fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is.
  • Invisible stray Unicode characters: In some cases, you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

    • Try grep --color -P -n "\[\x80-\xFF\]" file.php as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors \n newlines, not \r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS  X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldom disturb the parser when linebreaks get ignored.

  • If your syntax error does not transmit over the web:
    It happens that you have a syntax error on your machine. But posting the very same file online does not exhibit it anymore. Which can only mean one of two things:

    • You are looking at the wrong file!

    • Or your code contained invisible stray Unicode (see above).
      You can easily find out: Just copy your code back from the web form into your text editor.

  • Check your PHP version. Not all syntax constructs are available on every server.

    • php -v for the command line interpreter

    • <?php phpinfo(); for the one invoked through the webserver.

    Those aren’t necessarily the same. In particular when working with frameworks, you will them to match up.

  • Don’t use PHP’s reserved keywords as identifiers for functions/methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren’t as easy to search for (Stack Overflow itself is indexed by SymbolHound though). Therefore it may take looking through a few more pages before you find something relevant.

Further guides:

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your php.ini generally, or via .htaccess for mod_php,
or even .user.ini with FastCGI setups.

Enabling it within the broken script is too late because PHP can’t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

   ini_set("display_errors", 1);

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.


  • error_reporting(E_ALL | E_STRICT); for earlier versions of PHP

    – Geo

    Aug 15, 2013 at 21:42

  • 3

    Some IDEs (like NetBeans) not only support syntax highlighting but also code formatting. If you get into the habit of formatting your code properly and asking the IDE to reformat just in case from time to time you may catch hard to spot problems like unmatched braces.

    May 21, 2015 at 19:20



I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there’s absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You’ll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)


  • 3

    It is obviously. However, relisting IDEs here, can you elaborate a bit where they differ in their syntax helpfulness? Sublime is mostly an editor, not IDE; but then more pretty and snappy; does primarily just syntax highlighing but’s also veritable at bracket matching. It easily discovers T_CONSTANT_AND_ENCAPSED errors instantly for example, unlike PHPStorm; which however does more squiggly lines for inline errors. NetBeans´ syntax hints used to be more cryptic than PHPs even (relisting allowed constructs rather). Can you share your experience on pros/cons; is your favorite Eclipse/PDT or..?

    – mario

    Aug 12, 2013 at 20:31

  • @mario I think you are really deep into the topic so i really dont want to say anything wrong here, but all the code I (and my team mates, friends who code, freelance partners) have ever written in an IDE never ever was executed with a syntax error. So I think at least Netbeans/PHPStorm’s syntax check is extremely powerful. But maybe I’ve misread your question. Gimme some hours … 😉

    – Sliq

    Aug 12, 2013 at 21:03

  • Your answer is already spot on. Would fit 99% of our questions. However for the context here I’d like a trade-off consideration on which IDE provides the more newbie-friendly tooltips. It’s probably minor to us, colorization and squiggly lines being sufficient if you’re versed enough. But I presume the differences could be more significant to beginners.

    – mario

    Aug 12, 2013 at 21:29

  • Sometimes an IDE is not a feasible option. For example, making quick edits to a WordPress theme or plugin. Yes, I could copy all the code into an IDE, but then I have to open it up, paste it all in there, set headers and all that other time wasting crap, when I’m just hoping for a quick edit. Now, if you’re developing new features or starting from scratch, then, yes, do it in an IDE. You won’t regret taking that bit of extra time at the start to set it up.

    – 1934286

    Mar 6, 2017 at 16:22

  • I see IDE as a trailer, not just a toolbox. It might not FIX but it can help you find and prevent syntax errors. Many answer here seems to say that if you keep you code clean you have less chance to make an error and are easier to spot. Well with auto-indentation, code hints, variable occurrence, auto-closing brackets and auto-formatting saves me many typos a day and is the main advantage why i use one. This is not counting everything else beyond the scope of this question (debugger, database connector, uml diagram etc.) IDE will save you time and will prevent more than just syntax errors.

    Mar 27, 2017 at 4:48


Unexpected [

These days, the unexpected [ array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array().

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];

Array function result dereferencing is likewise not available for older PHP versions:

$result = get_whatever()["key"];

Reference – What does this error mean in PHP? – “Syntax error, unexpected \[ shows the most common and practical workarounds.

Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi can be used to enable a newer runtime.

See also:

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.

Other causes for Unexpected [ syntax errors

If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:

  • You can’t use array property declarations/expressions in classes, not even in PHP 7.

    protected $var["x"] = "Nope";
  • Confusing [ with opening curly braces { or parentheses ( is a common oversight.

    foreach [$a as $b)

    Or even:

    function foobar[$a, $b, $c] {
  • Or trying to dereference constants (before PHP 5.6) as arrays:

    $var = const[123];

    At least PHP interprets that const as a constant name.

    If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil – so it becomes a $varname.

  • You are trying to use the global keyword on a member of an associative array. This is not valid syntax:

    global $var['key'];

Unexpected ] closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array ] bracket.

  • Again mismatches with ) parentheses or } curly braces are common:

    function foobar($a, $b, $c] {
  • Or trying to end an array where there isn’t one:

    $var = 2];

    Which often occurs in multi-line and nested array declarations.

    $array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];

    If so, use your IDE for bracket matching to find any premature ] array closure. At the very least use more spacing and newlines to narrow it down.