Syntax error unexpected


Unexpected T_VARIABLE

An «unexpected » means that there’s a literal name, which doesn’t fit into the current expression/statement structure.

  1. It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:

  2. Btw, you should prefer (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.

  3. PHP can’t guess here if the variable should have been added, subtracted or compared etc.

  4. Lists

    Same for syntax lists, like in array populations, where the parser also indicates an expected comma for example:

    Or functions parameter lists:

    Equivalently do you see this with or statements, or when lacking a semicolon in a loop.

  5. Class declarations

    This parser error also occurs in class declarations. You can only assign static constants, not expressions. Thus the parser complains about variables as assigned data:

    Unmatched closing curly braces can in particular lead here. If a method is terminated too early (use proper indentation!), then a stray variable is commonly misplaced into the class declaration body.

  6. Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with for example.

  7. Missing parentheses after language constructs

    Hasty typing may lead to forgotten opening or closing parenthesis for and and statements:

    Solution: add the missing opening between statement and variable.

    The curly brace does not open the code block, without closing the expression with the closing parenthesis first.

  8. Solution: Remove the conditions from or use .

  9. Solution: Add brackets around .

  10. Invisible whitespace

    As mentioned in the reference answer on «Invisible stray Unicode» (such as a non-breaking space), you might also see this error for unsuspecting code like:

    It’s rather prevalent in the start of files and for copy-and-pasted code. Check with a hexeditor, if your code does not visually appear to contain a syntax issue.

Unexpected T_IF Unexpected T_FOREACH Unexpected T_FOR Unexpected T_WHILE Unexpected T_DO Unexpected T_ECHO

Control constructs such as , , , , , , , , , may only be used as statements. They usually reside on a line by themselves.

  1. Semicolon; where you at?

    Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement:

    Solution: look into the previous line; add semicolon.

  2. Class declarations

    Another location where this occurs is in class declarations. In the class section you can only list property initializations and method sections. No code may reside there.

    Such syntax errors commonly materialize for incorrectly nested and . In particular when function code blocks got closed too early.

  3. Statements in expression context

    Most language constructs can only be used as statements. They aren’t meant to be placed inside other expressions:

    Likewise can’t you use an in strings, math expressions or elsewhere:

    For embedding -like conditions in an expression specifically, you often want to use a ternary evaluation.

    The same applies to , , , and a lesser extend .

    Whereas is a language built-in that may be used in expression context. (But rarely makes sense.)

  4. You also can’t use or and other language constructs for user-defined functions or class names. (Perhaps in PHP 7. But even then it wouldn’t be advisable.)

  5. Your have a semi-colon instead of a colon (:) or curly bracket ({) after your control block

    Control structures are typically wrapped in curly braces (but colons can be used in an alternative syntax) to represent their scope. If you accidentally use a semi-colon you prematurely close that block resulting in your closing statement throwing an error.

Unexpected )

  1. Absent function parameter

    You cannot have stray commas last in a function call. PHP expects a value there and thusly complains about an early closing parenthesis.

    A trailing comma is only allowed in or constructs.

  2. Unfinished expressions

    If you forget something in an arithmetic expression, then the parser gives up. Because how should it possibly interpret that:

    And if you forgot the closing even, then you’d get a complaint about the unexpected semicolon instead.

  3. Foreach as

    For forgotten variable prefixes in control statements you will see:

    PHP here sometimes tells you it expected a instead. Because a class::$variable could have satisfied the expected $variable expression..

Unexpected {

Curly braces and enclose code blocks. And syntax errors about them usually indicate some incorrect nesting.

  1. Unmatched subexpressions in an

    Most commonly unbalanced and are the cause if the parser complains about the opening curly appearing too early. A simple example:

    Count your parentheses or use an IDE which helps with that. Also don’t write code without any spaces. Readability counts.

  2. { and } in expression context

    You can’t use curly braces in expressions. If you confuse parentheses and curlys, it won’t comply to the language grammar:

    There are a few exceptions for identifier construction, such as local scope variable .

  3. Variable variables or curly var expressions

    This is pretty rare. But you might also get and parser complaints for complex variable expressions:

    Though there’s a higher likelihood for an unexpected in such contexts.


The unwieldy names and refer to quoted 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:

    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 , because it usually expects a literal identifier / key there.

    More precisely it’s valid to use PHP2-style for array references:

    Nested arrays or deeper object references however require the 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:

    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.

    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.

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

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

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

  5. 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. The same thing for function calls:

  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

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

See also

Unexpected T_IS_EQUAL Unexpected T_IS_GREATER_OR_EQUAL Unexpected T_IS_IDENTICAL Unexpected T_IS_NOT_EQUAL Unexpected T_IS_NOT_IDENTICAL Unexpected T_IS_SMALLER_OR_EQUAL Unexpected < Unexpected >

Comparison operators such as , , , , , and or and mostly should be used just in expressions, such as expressions. If the parser complains about them, then it often means incorrect paring or mismatched parens around them.

  1. Parens grouping

    In particular for statements with multiple comparisons you must take care to correctly count opening and closing parenthesis:

    Here the condition here was already terminated by the

    Once your comparisons become sufficiently complex it often helps to split it up into multiple and nested constructs rather.

  2. A common newcomer is pitfal is trying to combine or with comparisons:

    Or even:

    This doesn’t make sense to PHP, because and are language constructs that only accept variable names. It doesn’t make sense to compare the result either, because the output is only/already a boolean.

  3. Confusing greater-or-equal with array operator

    Both operators look somewhat similar, so they sometimes get mixed up:

    You only need to remember that this comparison operator is called «greater than or equal» to get it right.

    See also: If statement structure in PHP

  4. Nothing to compare against

    You also can’t combine two comparisons if they pertain the same variable name:

    PHP can’t deduce that you meant to compare the initial variable again. Expressions are usually paired according to operator precedence, so by the time the is seen, there’d be only a boolean result left from the original variable.

    See also: unexpected T_IS_SMALLER_OR_EQUAL

  5. Comparison chains

    You can’t compare against a variable with a row of operators:

    This has to be broken up into two comparisons, each against .

    This is actually more a case of blacklisted expressions (due to equivalent operator associativity). It’s syntactically valid in a few C-style languages, but PHP wouldn’t interpret it as expected comparison chain either.

  6. Unexpected Unexpected

    The greater than or less than operators don’t have a custom tokenizer name. And while they can be misplaced like all they others, you more often see the parser complain about them for misquoted strings and mashed HTML:

    This amounts to a string being compared to a literal constant and then another comparison. Or that’s at least how PHP sees it. The actual cause and syntax mistake was the premature string termination.

    It’s also not possible to nest PHP start tags:

See also:

Unexpected }

When getting an «unexpected » error, you’ve mostly closed a code block too early.

  1. Last statement in a code block

    It can happen for any unterminated expression.

    And if the last line in a function/code block lacks a trailing semicolon:

    Here the parser can’t tell if you perhaps still wanted to add to the function result or something else.

  2. Invalid block nesting / Forgotten

    You’ll sometimes see this parser error when a code block was closed too early, or you forgot an opening even:

    In above snippet the didn’t have an opening curly brace. Thus the closing one below became redundant. And therefore the next closing , which was intended for the function, was not associable to the original opening curly brace.

    Such errors are even harder to find without proper code indentation. Use an IDE and bracket matching.

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 function result dereferencing is likewise not available for older PHP versions:

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. can be used to enable a newer runtime.

See also:

  • PHP syntax for dereferencing function result → possible as of PHP 5.4
  • PHP syntax error, unexpected ‘[‘
  • Shorthand for arrays: is there a literal syntax like {} or []?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘[‘
  • PHP Difference between array() and []
  • PHP Array Syntax Parse Error Left Square Bracket «[«

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.

  • Confusing with opening curly braces or parentheses is a common oversight.

    Or even:

  • Or trying to dereference constants (before PHP 5.6) as arrays:

    At least PHP interprets that 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 .

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

Unexpected closing square bracket

Unexpected (

Opening parentheses typically follow language constructs such as //// or start an arithmetic expression. They’re syntactically incorrect after , a previous , a lone , and in some typical declaration contexts.

  1. Function declaration parameters

    A rarer occurrence for this error is trying to use expressions as default function parameters. This is not supported, even in PHP7:

    Parameters in a function declaration can only be literal values or constant expressions. Unlike for function invocations, where you can freely use , etc.

  2. Class property defaults

    Same thing for class member declarations, where only literal/constant values are allowed, not expressions:

    Put such things in the constructor. See also Why don’t PHP attributes allow functions?

    Again note that PHP 7 only allows constant expressions there.

  3. When this happens, it usually indicates an unterminated preceding string; and literal sections leaking into PHP code context.

  4. isset(()), empty, key, next, current

    Both and are language built-ins, not functions. They need to access a variable directly. If you inadvertently add a pair of parentheses too much, then you’d create an expression however:

    The same applies to any language construct that requires implicit variable name access. These built-ins are part of the language grammar, therefore don’t permit decorative extra parentheses.

    User-level functions that require a variable reference -but get an expression result passed- lead to runtime errors instead.

Unexpected $end

When PHP talks about an «unexpected «, it means that your code ended prematurely. (The message is a bit misleading when taken literally. It’s not about a variable named «$end», as sometimes assumed by newcomers. It refers to the «end of file», EOF.)

It’s pretty much always about a missing curly brace to close preceding code blocks.

  • Again, use proper indentation to avoid such issues.

  • Use an IDE with bracket matching, to find out where the is amiss. There are keyboard shortcuts in most IDEs and text editors:

    • NetBeans, PhpStorm, Komodo: Ctrl and Ctrl
    • Eclipse, Aptana: CtrlShiftP
    • Atom, Sublime: Ctrlm — Zend Studio CtrlM
    • Geany, Notepad++: CtrlB — Joe: CtrlG — Emacs: C-M-n — Vim: %

Most IDEs also highlight matching braces, brackets and parentheses. Which makes it pretty easy to inspect their correlation:

Unterminated expressions

And syntax/parser error can also occur for unterminated expressions or statements:

$var = func(1, ?>EOF

So, look at the end of scripts first. A trailing is often redundant for the last statement in any PHP script. But you should have one. Precisely because it narrows such syntax issues down.

Indented HEREDOC markers

Another common occurrence appears with strings. The terminating marker goes ignored with leading spaces, tabs, etc.:

Therefore the parser assumes the HEREDOC string to continue until the end of the file (hence «Unexpected $end»). Pretty much all IDEs and syntax-highlighting editors will make this obvious or warn about it.

Escaped Quotation marks

If you use in a string, it has a special meaning. This is called an «Escape Character» and normally tells the parser to take the next character literally.

Example: will print

If you escape the closing quote of a string, the closing quote will be taken literally and not as intended, i.e. as a printable quote as part of the string and not close the string. This will show as a parse error commonly after you open the next string or at the end of the script.

Very common error when specifiying paths in Windows: is wrong. You need .

Alternative syntax

Somewhat rarer you can see this syntax error when using the alternative syntax for statement/code blocks in templates. Using and and a missing for example.

С этим читают