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 {