parsing - PHP parse/syntax errors; and how to solve them ← (PHP, Laravel, JavaScript, MySQL, HTML)

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 '{-code-1}' 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 . This references summarized the common pitfalls:

Closely related references:

And:

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

If your browser displays error messages such as "SyntaxError: illegal character", then it's not actually php-related, but a javascript-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.

Answer



Solution:

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 ident{-code-18}-code-11}iers. It can{-code-18}-code-8}t guess your coding intentions.

{-code-18}-code-7}Function

Most important tips

There are a few basic precautions you can always take:

How to interpret parser errors

A typical syntax error message reads:

Parse error: syntax error, unexpected {-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5}, expecting {-code-18}-code-8}{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}{-code-18}-code-8} 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 {-code-18}-code-4{-code-18}-code-5}-code-2{-code-18}-code-5} explains which symbol the parser/tokenizer couldn{-code-18}-code-8}t process finally. This isn{-code-18}-code-8}t necessarily the cause of the syntax mistake, however.

It{-code-18}-code-8}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.

If all else fails, you can always google your error message. Syntax symbols aren{-code-18}-code-8}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 generally, or via for mod_php, or even with FastCGI setups.

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

<{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php
   error_reporting(E_ALL){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   ini_set({-code-18}-code-7}display_errors{-code-18}-code-7}, 1){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   include({-code-18}-code-7}./broken-script.php{-code-18}-code-7}){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP{-code-18}-code-8}s error_log and look into your webserver{-code-18}-code-8}s when a script crashes with HTTP 500 responses.

Answer



Solution:

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)

Answer



Solution:

Unexpected {-code-11}-code-1}

These days, the unexpected {-code-11}-code-1} array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support {-code-11}-code-3}.

{-code-17}php53 = array{-code-12}1, 2, 3{-code-23};
{-code-17}php54 = {-code-11}-code-1}1, 2, 3{-code-21};
         ⇑

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

{-code-17}result = get_whatever{-code-12}{-code-23}{-code-11}-code-1}"key"{-code-21};
                      ⇑

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. {-code-11}-code-7} 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 {-code-11}-code-1} 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 {-code-17}var{-code-11}-code-1}"x"{-code-21} = "Nope";
                  ⇑
    
  • Confusing {-code-11}-code-1} with opening curly braces {-code-11} or parentheses {-code-12} is a common oversight.

    foreach {-code-11}-code-1}{-code-17}a as {-code-17}b{-code-23}
            ⇑
    

    Or even:

    function foobar{-code-11}-code-1}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                   ⇑
    
  • Or trying to dereference {-code-16}ants {-code-12}before PHP 5.6{-code-23} as arrays:

    {-code-17}var = {-code-16}{-code-11}-code-1}123{-code-21};
           ⇑
    

    At least PHP interprets that {-code-16} as a {-code-16}ant name.

    If you meant to access an array variable {-code-12}which is the typical cause here{-code-23}, then add the leading {-code-17} sigil - so it becomes a {-code-17}varname.

  • You are trying to use the {-code-19} keyword on a member of an associative array. This is not valid syntax:

    {-code-19} {-code-17}var{-code-11}-code-1}'key'{-code-21};
    


Unexpected {-code-21} closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array {-code-21} bracket.

  • Again mismatches with {-code-23} parentheses or } curly braces are common:

    function foobar{-code-12}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                              ⇑
    
  • Or trying to end an array where there isn't one:

    {-code-17}var = 2{-code-21};
    

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

    {-code-17}array = {-code-11}-code-1}1,{-code-11}-code-1}2,3{-code-21},4,{-code-11}-code-1}5,6{-code-11}-code-1}7,{-code-11}-code-1}8{-code-21},{-code-11}-code-1}9,10{-code-21}{-code-21},11{-code-21},12{-code-21}{-code-21},15{-code-21};
                                                 ⇑
    

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

Answer



Solution:

Unexpected {-code-1{-code-16}

An "{-code-13{-code-16}unexpected {-code-1{-code-16}"{-code-13{-code-16} means that there's a literal {-code-2{-code-16} name{-code-8{-code-16} which doesn't fit into the current expression/statement structure{-code-4{-code-16}

purposefully abstract/inexact operator+{-code-2{-code-16} diagram

  1. Missing semicolon

    It most commonly indicates a missing semicolon in the previous line{-code-4{-code-16} Variable assignments following a statement are a good indicator where to look:

            {-code-3{-code-16}
    
  2. String concatenation

    A frequent mishap are string concatenations with {-code-14{-code-16}gotten {-code-4{-code-16} operator:

                                    {-code-5{-code-16}
    

    Btw{-code-8{-code-16} you should prefer string interpolation {-code-23}basic variables in double quotes) whenever that helps readability{-code-4{-code-16} Which avoids these syntax issues{-code-4{-code-16}

    String interpolation is a scripting language core feature{-code-4{-code-16} No shame in utilizing it{-code-4{-code-16} Ignore any micro-optimization advise about variable {-code-4{-code-16} concatenation being faster{-code-4{-code-16} It's not{-code-4{-code-16}

  3. Missing expression operators

    Of course the same issue can arise in other expressions{-code-8{-code-16} {-code-14{-code-16} instance arithmetic operations:

                {-code-7{-code-16}
    

    PHP can't guess here {-code-19} the variable should have been added{-code-8{-code-16} subtracted or compared etc{-code-4{-code-16}

  4. Lists

    Same {-code-14{-code-16} syntax {-code-11{-code-16}s{-code-8{-code-16} like in array populations{-code-8{-code-16} where the parser also indicates an expected comma {-code-8{-code-16} {-code-14{-code-16} example:

                                           ⇓
     $var = array{-code-23}"{-code-13{-code-16}1"{-code-13{-code-16} =>{-code-13{-code-16} $val{-code-8{-code-16} $val2{-code-8{-code-16} $val3 $val4){-code-13{-code-16}
    

    Or functions parameter {-code-11{-code-16}s:

                                     ⇓
     function myfunc{-code-23}$param1{-code-8{-code-16} $param2 $param3{-code-8{-code-16} $param4)
    

    Equivalently do you see this with {-code-11{-code-16} or {-code-12{-code-16} statements{-code-8{-code-16} or when lacking a {-code-13{-code-16} semicolon in a {-code-14{-code-16} loop{-code-4{-code-16}

  5. Class declarations

    This parser error also occurs in class declarations{-code-4{-code-16} You can only assign static constants{-code-8{-code-16} not expressions{-code-4{-code-16} Thus the parser complains about variables as assigned data:

     class xyz {      ⇓
         var $value = $_GET["{-code-13{-code-16}input"{-code-13{-code-16}]{-code-13{-code-16}
    

    Unmatched {-code-16} closing curly braces can in particular lead here{-code-4{-code-16} If a method is terminated too early {-code-23}use proper indentation!){-code-8{-code-16} then a stray variable is commonly misplaced into the class declaration body{-code-4{-code-16}

  6. Variables after ident{-code-19}iers

    You can also never have a variable follow an ident{-code-19}ier directly:

                  ⇓
     $this->{-code-13{-code-16}myFunc$VAR{-code-23}){-code-13{-code-16}
    

    Btw{-code-8{-code-16} this is a common example where the intention was to use variable variables perhaps{-code-4{-code-16} In this case a variable property lookup with $this->{-code-13{-code-16}{"{-code-13{-code-16}myFunc$VAR"{-code-13{-code-16}{-code-16}{-code-23}){-code-13{-code-16} {-code-14{-code-16} example{-code-4{-code-16}

    Take in mind that using variable variables should be the exception{-code-4{-code-16} Newcomers often try to use them too casually{-code-8{-code-16} even when arrays would be simpler and more appropriate{-code-4{-code-16}

  7. Missing parentheses after language constructs

    Hasty typing may lead to {-code-14{-code-16}gotten opening or closing parenthesis {-code-14{-code-16} {-code-19} and {-code-14{-code-16} and {-code-14{-code-16}each statements:

            ⇓
     {-code-14{-code-16}each $array as $key) {
    

    Solution: add the missing opening {-code-23} between statement and variable{-code-4{-code-16}

                           ⇓
     {-code-19} {-code-23}$var = pdo_query{-code-23}$sql) {
          $result = …
    

    The curly { brace does not open the code block{-code-8{-code-16} without closing the {-code-19} expression with the ) closing parenthesis first{-code-4{-code-16}

  8. Else does not expect conditions

         ⇓
    else {-code-23}$var >{-code-13{-code-16}= 0)
    

    Solution: Remove the conditions from else or use {-code-4{-code-16}

  9. Need brackets {-code-14{-code-16} closure

         ⇓
    function{-code-23}) use $var {{-code-16}
    

    Solution: Add brackets around $var{-code-4{-code-16}

  10. Invisible whitespace

    As mentioned in the reference answer on "{-code-13{-code-16}Invisible stray Unicode"{-code-13{-code-16} {-code-23}such as a non-breaking space){-code-8{-code-16} you might also see this error {-code-14{-code-16} unsuspecting code like:

    <{-code-13{-code-16}?php
                              ⇐
    $var = new PDO{-code-23}{-code-4{-code-16}{-code-4{-code-16}{-code-4{-code-16}){-code-13{-code-16}
    

    It's rather prevalent in the start of files and {-code-14{-code-16} copy-and-pasted code{-code-4{-code-16} Check with a hexeditor{-code-8{-code-16} {-code-19} your code does not visually appear to contain a syntax issue{-code-4{-code-16}

See also

Answer



Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy names T_CONSTANT_ENCAPSED_STRING and T_ENCAPSED_AND_WHITESPACE refer to quoted "string" literals.

They're used in different contexts, but the syntax issue are quite similar. T_ENCAPSED… warnings occur in double quoted string context, while T_CONSTANT… strings are often astray in plain PHP expressions or statements.

  1. Incorrect variable interpolation

    And it comes up most frequently for incorrect PHP variable interpolation:

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    Quoting arrays keys is a must in PHP context. But in double quoted strings (or HEREDOCs) this is a mistake. The parser complains about the contained single quoted 'string', because it usually expects a literal identifier / key there.

    More precisely it's valid to use PHP2-style simple syntax within double quotes for array references:

    echo "This is only $valid[here] ...";
    

    Nested arrays or deeper object references however require the complex curly string expression syntax:

    echo "Use {$array['as_usual']} with curly syntax.";
    

    If unsure, this is commonly safer to use. It's often even considered more readable. And better IDEs actually use distinct syntax colorization for that.

  2. Missing concatenation

    If a string follows an expression, but lacks a concatenation or other operator, then you'll see PHP complain about the string literal:

                           ⇓
    print "Hello " . WORLD  " !";
    

    While it's obvious to you and me, PHP just can't guess that the string was meant to be appended there.

  3. Confusing string quote enclosures

    The same syntax error occurs when confounding string delimiters. A string started by a single ' or double " quote also ends with the same.

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          ⌞⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟⌞⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⎽⌟
    

    That example started with double quotes. But double quotes were also destined for the HTML attributes. The intended concatenation operator within however became interpreted as part of a second string in single quotes.

    Tip: Set your editor/IDE to use slightly distinct colorization for single and double quoted strings. (It also helps with application logic to prefer e.g. double quoted strings for textual output, and single quoted strings only for constant-like values.)

    This is a good example where you shouldn't break out of double quotes in the first place. Instead just use proper for the HTML attributes´ quotes:

    print "<a href=\"{$link}\">click here</a>";
    

    While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently.

  4. Missing opening quote

    Equivalently are forgotten opening a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

    Here the ', ' would become a string literal after a bareword, when obviously login was meant to be a string parameter.

  5. Array lists

    If you miss a , comma in an array creation block, the parser will see two consecutive strings:

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    

    Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    

    Here PHP complains about two string literals directly following each other. But the real cause is the unclosed previous string of course.

  8. HEREDOC indentation

    Prior PHP 7.3, the heredoc string end delimiter can't be prefixed with spaces:

    print <<< HTML
        <link..>
        HTML;
       ⇑
    

    Solution: upgrade PHP or find a better hoster.

See also

Answer



Solution:

Unexpected

is a bit of a misnomer. It does not refer to a quoted {-code-2}. It means a raw identifier was encountered. This can range from {-code-3} words to leftover {-code-4} or function names, forgotten unquoted strings, or any plain text.

  1. Misquoted strings

    This syntax error is most common for misquoted string values however. Any unescaped and stray {-code-5} or {-code-6} quote will form an invalid expression:

                   ⇓                  ⇓
     {-code-11} {-code-5}<{-code-29}a href={-code-5}http://example.com{-code-5}>{-code-29}click here<{-code-29}/a>{-code-29}{-code-5}{-code-29}
    

    Syntax highlighting will make such mistakes super obvious. It{-code-6}s important to remember to use backslashes for escaping {-code-33}{-code-5} double quotes, or {-code-33}{-code-6} single quotes - depending on which was used as string enclosure.

    • For convenience you should prefer outer single quotes when outputting plain HTML with double quotes within.
    • Use double quoted strings if you want to interpolate variables, but then watch out for escaping literal {-code-5} double quotes.
    • For lengthier output, prefer multiple {-code-11}/{-code-12} lines instead of escaping in and out. Better yet consider a HEREDOC section.


    Another example is using PHP entry inside HTML code generated with PHP:

    {-code-14} = {-code-6}<{-code-29}div>{-code-29}some text with {-code-25}php {-code-11} {-code-6}some php entry{-code-6} ?>{-code-29}<{-code-29}/div>{-code-29}{-code-6}
    

    This happens if {-code-14} is large with many lines and developer does not see the whole PHP variable value and focus on the piece of code forgetting about its source. Example is here

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ⇓
    {-code-11} {-code-5}Some text{-code-5}, {-code-32}a_variable, {-code-5}and some runaway string {-code-29}
    success({-code-5}finished{-code-5}){-code-29}
             ⇯
    

    It{-code-6}s not just literal s which the parser may protest then. Another frequent variation is an for unquoted literal HTML.

  3. Non-programming string quotes

    If you copy and paste code from a blog or website, you sometimes end up with invalid code. Typographic quotes aren{-code-6}t what PHP expects:

    {-code-14} = ’Something something..’ + {-code-20} ain{-code-6}t quotes”{-code-29}
    

    Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example {-code-20} is interpreted as a constant identifier. But any following text literal is then seen as a {-code-3}word/ by the parser.

  4. The missing semicolon{-code-29} again

    If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:

           {-code-21}
    

    PHP just can{-code-6}t know if you meant to run two functions after another, or if you meant to multiply their results, add them, compare them, or only run one {-code-22} or the other.

  5. Short open tags and {-code-23} headers in PHP scripts

    This is rather uncommon. But if short_open_tags are enabled, then you can{-code-6}t begin your PHP scripts with an XML declaration:

          ⇓
    {-code-23} {-code-27}={-code-5}1.0{-code-5}?>{-code-29}
    

    PHP will see the {-code-25} and reclaim it for itself. It won{-code-6}t understand what the stray {-code-26} was meant for. It{-code-6}ll get interpreted as constant. But the {-code-27} will be seen as another literal/constant. And since the parser can{-code-6}t make sense of two subsequent literals/values without an expression operator in between, that{-code-6}ll be a parser failure.

  6. Invisible Unicode characters

    A most hideous cause for syntax errors are Unicode symbols, such as the

    Source