20 回答
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.
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.
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 nestedif
conditions.Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)
Add newlines between:
- The code you can easily identify as correct,
- The parts you're unsure about,
- 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 plainif
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.
- Adopt a source code versioning system. You can always view a
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:
- PHP Debugging Basics by David Sklar
- Fixing PHP Errors by Jason McCreary
- PHP Errors – 10 Common Mistakes by Mario Lurig
- Common PHP Errors and Solutions
- How to Troubleshoot and Fix your WordPress Website
- A Guide To PHP Error Messages For Designers - Smashing Magazine
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
:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("./broken-script.php");
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.
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):
- NetBeans [free]
- PHPStorm [$199 USD]
- Eclipse with PHP Plugin [free]
- Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)
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:
- 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.
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.
Unexpected T_VARIABLE
An "unexpected T_VARIABLE
" means that there's a literal $variable
name, which doesn't fit into the current expression/statement structure.
Missing semicolon
It most commonly indicates a missing semicolon in the previous line. Variable assignments following a statement are a good indicator where to look:
⇓ func1() $var = 1 + 2; # parse error in line +2
String concatenation
A frequent mishap are string concatenations with forgotten
.
operator:⇓ print "Here comes the value: " $value;
Btw, you should prefer string interpolation (basic variables in double quotes) whenever that helps readability. Which avoids these syntax issues.
String interpolation is a scripting language core feature. No shame in utilizing it. Ignore any micro-optimization advise about variable
.
concatenation being faster. It's not.Missing expression operators
Of course the same issue can arise in other expressions, for instance arithmetic operations:
⇓ print 4 + 7 $var;
PHP can't guess here if the variable should have been added, subtracted or compared etc.
Lists
Same for syntax lists, like in array populations, where the parser also indicates an expected comma
,
for example:⇓ $var = array("1" => $val, $val2, $val3 $val4);
Or functions parameter lists:
⇓ function myfunc($param1, $param2 $param3, $param4)
Equivalently do you see this with
list
orglobal
statements, or when lacking a;
semicolon in afor
loop.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:
class xyz { ⇓ var $value = $_GET["input"];
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.Variables after identifiers
You can also never have a variable follow an identifier directly:
⇓ $this->myFunc$VAR();
Btw, this is a common example where the intention was to use variable variables perhaps. In this case a variable property lookup with
$this->{"myFunc$VAR"}();
for example.Take in mind that using variable variables should be the exception. Newcomers often try to use them too casually, even when arrays would be simpler and more appropriate.
Missing parentheses after language constructs
Hasty typing may lead to forgotten opening or closing parenthesis for
if
andfor
andforeach
statements:⇓ foreach $array as $key) {
Solution: add the missing opening
(
between statement and variable.⇓ if ($var = pdo_query($sql) { $result = …
The curly
{
brace does not open the code block, without closing theif
expression with the)
closing parenthesis first.Else does not expect conditions
⇓ else ($var >= 0)
Solution: Remove the conditions from
else
or useelseif
.Need brackets for closure
⇓ function() use $var {}
Solution: Add brackets around
$var
.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:
<?php ⇐ $var = new PDO(...);
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.
See also
Unexpected T_STRING
T_STRING
is a bit of a misnomer. It does not refer to a quoted "string"
. It means a raw identifier was encountered. This can range from bare
words to leftover CONSTANT
or function names, forgotten unquoted strings, or any plain text.
Misquoted strings
This syntax error is most common for misquoted string values however. Any unescaped and stray
"
or'
quote will form an invalid expression:⇓ ⇓ echo "<a href="http://example.com">click here</a>";
Syntax highlighting will make such mistakes super obvious. It's important to remember to use backslashes for escaping
\"
double quotes, or\'
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
"
double quotes. - For lengthier output, prefer multiple
echo
/print
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:$text = '<div>some text with <?php echo 'some php entry' ?></div>'
This happens if
$text
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 hereSee also What is the difference between single-quoted and double-quoted strings in PHP?.
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:⇓ echo "Some text", $a_variable, "and some runaway string ; success("finished"); ⇯
It's not just literal
T_STRING
s which the parser may protest then. Another frequent variation is anUnexpected '>'
for unquoted literal HTML.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't what PHP expects:
$text = ’Something something..’ + ”these ain't quotes”;
Typographic/smart quotes are Unicode symbols. PHP treats them as part of adjoining alphanumeric text. For example
”these
is interpreted as a constant identifier. But any following text literal is then seen as a bareword/T_STRING by the parser.The missing semicolon; again
If you have an unterminated expression in previous lines, then any following statement or language construct gets seen as raw identifier:
⇓ func1() function2();
PHP just can'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
||
or the other.Short open tags and
<?xml
headers in PHP scriptsThis is rather uncommon. But if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration:
⇓ <?xml version="1.0"?>
PHP will see the
<?
and reclaim it for itself. It won't understand what the strayxml
was meant for. It'll get interpreted as constant. But theversion
will be seen as another literal/constant. And since the parser can't make sense of two subsequent literals/values without an expression operator in between, that'll be a parser failure.Invisible Unicode characters
A most hideous cause for syntax errors are Unicode symbols, such as the non-breaking space. PHP allows Unicode characters as identifier names. If you get a T_STRING parser complaint for wholly unsuspicious code like:
<?php print 123;
You need to break out another text editor. Or an hexeditor even. What looks like plain spaces and newlines here, may contain invisible constants. Java-based IDEs are sometimes oblivious to an UTF-8 BOM mangled within, zero-width spaces, paragraph separators, etc. Try to reedit everything, remove whitespace and add normal spaces back in.
You can narrow it down with with adding redundant
;
statement separators at each line start:<?php ;print 123;
The extra
;
semicolon here will convert the preceding invisible character into an undefined constant reference (expression as statement). Which in return makes PHP produce a helpful notice.The `$` sign missing in front of variable names
Variables in PHP are represented by a dollar sign followed by the name of the variable.
The dollar sign (
$
) is a sigil that marks the identifier as a name of a variable. Without this sigil, the identifier could be a language keyword or a constant.This is a common error when the PHP code was "translated" from code written in another language (C, Java, JavaScript, etc.). In such cases, a declaration of the variable type (when the original code was written in a language that uses typed variables) could also sneak out and produce this error.
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:
echo 'Jim said \'Hello\'';
will printJim said 'hello'
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:
"C:\xampp\htdocs\"
is wrong. You need"C:\\xampp\\htdocs\\"
.Typed properties
You need PHP ≥7.4 to use property typing such as:
public stdClass $obj;
Unexpected (
Opening parentheses typically follow language constructs such as if
/foreach
/for
/array
/list
or start an arithmetic expression. They're syntactically incorrect after "strings"
, a previous ()
, a lone $
, and in some typical declaration contexts.
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:
function header_fallback($value, $expires = time() + 90000) {
Parameters in a function declaration can only be literal values or constant expressions. Unlike for function invocations, where you can freely use
whatever(1+something()*2)
, etc.Class property defaults
Same thing for class member declarations, where only literal/constant values are allowed, not expressions:
class xyz { ⇓ var $default = get_config("xyz_default");
Put such things in the constructor. See also Why don't PHP attributes allow functions?
Again note that PHP 7 only allows
var $xy = 1 + 2 +3;
constant expressions there.JavaScript syntax in PHP
Using JavaScript or jQuery syntax won't work in PHP for obvious reasons:
<?php ⇓ print $(document).text();
When this happens, it usually indicates an unterminated preceding string; and literal
<script>
sections leaking into PHP code context.isset(()), empty, key, next, current
Both
isset()
andempty()
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:⇓ if (isset(($_GET["id"]))) {
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 )
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.⇓ callfunc(1, 2, );
A trailing comma is only allowed in
array()
orlist()
constructs.Unfinished expressions
If you forget something in an arithmetic expression, then the parser gives up. Because how should it possibly interpret that:
⇓ $var = 2 * (1 + );
And if you forgot the closing
)
even, then you'd get a complaint about the unexpected semicolon instead.Foreach as
constant
For forgotten variable
$
prefixes in control statements you will see:↓ ⇓ foreach ($array as wrong) {
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.
Unmatched subexpressions in an
if
Most commonly unbalanced
(
and)
are the cause if the parser complains about the opening curly{
appearing too early. A simple example:⇓ if (($x == $y) && (2 == true) {
Count your parentheses or use an IDE which helps with that. Also don't write code without any spaces. Readability counts.
{ 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:
⇓ $var = 5 * {7 + $x};
There are a few exceptions for identifier construction, such as local scope variable
${references}
.Variable variables or curly var expressions
This is pretty rare. But you might also get
{
and}
parser complaints for complex variable expressions:⇓ print "Hello {$world[2{]} !";
Though there's a higher likelihood for an unexpected
}
in such contexts.
Unexpected }
When getting an "unexpected }
" error, you've mostly closed a code block too early.
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:function whatever() { doStuff() } ⇧
Here the parser can't tell if you perhaps still wanted to add
+ 25;
to the function result or something else.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:function doStuff() { if (true) ⇦ print "yes"; } } ⇧
In above snippet the
if
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 {
, expecting (
Language constructs which require a condition/declaration header and a code block will trigger this error.
Parameter lists
For example misdeclared functions without parameter list are not permitted:
⇓ function whatever { }
Control statement conditions
And you can't likewise have an
if
without condition.⇓ if { }
Which doesn't make sense, obviously. The same thing for the usual suspects,
for
/foreach
,while
/do
, etc.If you've got this particular error, you definitely should look up some manual examples.
Unexpected $end
When PHP talks about an "unexpected $end
", 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.)
Cause: Unbalanced
{
and}
for code blocks / and function or class declarations.
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 Unexpected $end
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 HEREDOC or NOWDOC strings. The terminating marker goes ignored with leading spaces, tabs, etc.:
print <<< END
Content...
Content....
END;
# ↑ terminator isn't exactly at the line start
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: echo 'Jim said \'Hello\'';
will print Jim said 'hello'
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: "C:\xampp\htdocs\"
is wrong. You need "C:\\xampp\\htdocs\\"
.
Alternative syntax
Somewhat rarer you can see this syntax error when using the alternative syntax for statement/code blocks in templates. Using if:
and else:
and a missing endif;
for example.
See also:
- PHP syntax error “unexpected $end”</a>
- Parse error: Syntax error, unexpected end of file in my PHP code
- Parse error syntax error unexpected end of file, using PHP
- PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View
- Parse error: syntax error, unexpected end of file (Registration script)
- "Parse error: syntax error, unexpected $end" For my uni registration assignment
- Fixing PHP Errors: PHP Error #3: Unexpected end of file
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 if
expressions. If the parser complains about them, then it often means incorrect paring or mismatched (
)
parens around them.
Parens grouping
In particular for
if
statements with multiple comparisons you must take care to correctly count opening and closing parenthesis:⇓ if (($foo < 7) && $bar) > 5 || $baz < 9) { ... } ↑
Here the
if
condition here was already terminated by the)
Once your comparisons become sufficiently complex it often helps to split it up into multiple and nested
if
constructs rather.isset() mashed with comparing
A common newcomer is pitfal is trying to combine
isset()
orempty()
with comparisons:⇓ if (empty($_POST["var"] == 1)) {
Or even:
⇓ if (isset($variable !== "value")) {
This doesn't make sense to PHP, because
isset
andempty
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.Confusing
>=
greater-or-equal with=>
array operatorBoth operators look somewhat similar, so they sometimes get mixed up:
⇓ if ($var => 5) { ... }
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
Nothing to compare against
You also can't combine two comparisons if they pertain the same variable name:
⇓ if ($xyz > 5 and < 100)
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
Comparison chains
You can't compare against a variable with a row of operators:
⇓ $reult = (5 < $x < 10);
This has to be broken up into two comparisons, each against
$x
.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.
Unexpected
>
Unexpected<
The greater than
>
or less than<
operators don't have a customT_XXX
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:⇓ print "<a href='z">Hello</a>"; ↑
This amounts to a string
"<a href='z"
being compared>
to a literal constantHello
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:
<?php echo <?php my_func(); ?> ↑
See also:
Unexpected T_IF
Unexpected T_FOREACH
Unexpected T_FOR
Unexpected T_WHILE
Unexpected T_DO
Unexpected T_ECHO
Control constructs such as if
, foreach
, for
, while
, list
, global
, return
, do
, print
, echo
may only be used as statements. They usually reside on a line by themselves.
Semicolon; where you at?
Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement:
⇓ $x = myfunc() if (true) {
Solution: look into the previous line; add semicolon.
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.
class xyz { if (true) {} foreach ($var) {}
Such syntax errors commonly materialize for incorrectly nested
{
and}
. In particular when function code blocks got closed too early.Statements in expression context
Most language constructs can only be used as statements. They aren't meant to be placed inside other expressions:
⇓ $var = array(1, 2, foreach($else as $_), 5, 6);
Likewise can't you use an
if
in strings, math expressions or elsewhere:⇓ print "Oh, " . if (true) { "you!" } . " won't work"; // Use a ternary condition here instead, when versed enough.
For embedding
if
-like conditions in an expression specifically, you often want to use a?:
ternary evaluation.The same applies to
for
,while
,global
,echo
and a lesser extendlist
.⇓ echo 123, echo 567, "huh?";
Whereas
print()
is a language built-in that may be used in expression context. (But rarely makes sense.)Reserved keywords as identifiers
You also can't use
do
orif
and other language constructs for user-defined functions or class names. (Perhaps in PHP 7. But even then it wouldn't be advisable.)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.
foreach ($errors as $error); <-- should be : or {
Unexpected '?'
If you are trying to use <?php
within <?php
this error will be given*.
$var = 'hello '<?php echo 'world'; ?>;
* For PHP versions 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1, 5.0.0 - 5.0.5, 4.4.2 - 4.4.9, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.31, 7.4.0 - 7.4.24
If you are trying to use the null coalescing operator ??
in a version of PHP prior to PHP 7 you will get this error.
<?= $a ?? 2; // works in PHP 7+
<?= (!empty($a)) ? $a : 2; // All versions of PHP
Unexpected '?', expecting variable
A similar error can occur for nullable types, as in:
function add(?int $sum): ?int {
Which again indicates an outdated PHP version being used (either the CLI version php -v
or the webserver bound one phpinfo();
).
Unexpected '='
This can be caused by having invalid characters in a variable name. Variables names must follow these rules:
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Unexpected 'endwhile' (T_ENDWHILE)
The syntax is using a colon - if there is no colon the above error will occur.
<?php while($query->fetch()): ?>
....
<?php endwhile; ?>
The alternative to this syntax is using curly brackets:
<?php while($query->fetch()) { ?>
....
<?php } ?>
Unexpected '.'
This can occur if you are trying to use the splat operator(...
) in an unsupported version of PHP.
...
first became available in PHP 5.6 to capture a variable number of arguments to a function:
function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES
In PHP 7.4, you could use it for Array expressions.
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
Unexpected :
1. PHP 8 named parameter syntax
unexpected ':', expecting ',' or ')'
If attempting to use PHP 8's new named parameter functionality in a version of PHP < 8 this error will occur:
$table->string(column:'Name');
Solutions:
- Upgrade your version of PHP to PHP 8.0.0 or higher
- Do not use named parameters (pass the parameters in the order they are expected)
2. Cropped class ::
separator
An error message that begins Parse error: syntax error, unexpected ':' can be caused by mistakenly writing a class static reference Class::$Variable
as Class:$Variable
.
Unexpected 'continue' (T_CONTINUE)
continue
is a statement (like for, or if) and must appear standalone. It cannot be used as part of an expression. Partly because continue doesn't return a value, but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.
That means continue
cannot be used in a ternary statement or any statement that requires a return value.
Unexpected 'break' (T_BREAK)
Same goes for break;
of course. It's also not usable in expression context, but a strict statement (on the same level as foreach
or an if
block).
Unexpected 'return' (T_RETURN)
Now this might be more surprising for return
, but that's also just a block-level statement. It does return a value (or NULL) to the higher scope/function, but it does not evaluate as expression itself. → That is: there's no point in doing return(return(false);;
One more reason to occurrence of these errors is unexpected whitespace like similar characters with-in code, the code lines seems to be perfect, but they contains some specific characters which are similar to break line or whitespace or tab but they not get parsed by the parser. I face this issue when I try to put some code from webpage to the code editor by simply copy paste, I saw this error with array definition. everything was looking right in array definition. I can't sort out right error, finally I define this array in single line, then error was gone. then again I try to make that definition multiple like but manually adding break(Enter) for each array element and saved the file this time no parsing error by editor and also no error while running it. For Example I faced issue with this snippet which was on one blog, actually can't post those snippets ,cause stack overflow already knows the problem with code.
then after solving it my working snippet is, which looks similar with one which shows parsing error
syntax error, unexpected ''auth'' (T_CONSTANT_ENCAPSED_STRING), expecting ']'
public $aliases = [
'csrf'=> \CodeIgniter\Filters\CSRF::class,
'toolbar'=> \CodeIgniter\Filters\DebugToolbar::class,
'honeypot'=> \CodeIgniter\Filters\Honeypot::class,
'auth' => \App\Filters\Auth::class,
];
For newbies to VS Code, if you see the syntax error, check if you have saved the file. If you have a wrong syntax, save the file, and then fix the syntax withou saving again, VS Code will keep showing you the error. The error message will disappear only after you save the file.