Syntax error unexpected expecting expression

parsing — 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 […]

Содержание

  1. parsing — PHP parse/syntax errors; and how to solve them
  2. Answer
  3. Solution:
  4. What are the syntax errors?
  5. Most important tips
  6. How to interpret parser errors
  7. Solving syntax errors
  8. White screen of death
  9. Answer
  10. Solution:
  11. Using a syntax-checking IDE means:
  12. Answer
  13. Solution:
  14. Unexpected <-code-11>-code-1>
  15. Unexpected <-code-21>closing square bracket
  16. Answer
  17. Solution:
  18. Unexpected An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-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 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: String concatenation 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 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 Missing expression operators Of course the same issue can arise in other expressions <-code-8<-code-16> <-code-14<-code-16>instance arithmetic operations: PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc Lists Or functions parameter <-code-11<-code-16>s: 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: 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 Variables after ident<-code-19>iers 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 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: Solution: add the missing opening <-code-23>between statement and variable The curly < brace does not open the code block<-code-8<-code-16>without closing the <-code-19>expression with the ) closing parenthesis first Else does not expect conditions Solution: Remove the conditions from else or use Need brackets <-code-14<-code-16>closure Solution: Add brackets around $var Invisible whitespace As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-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: 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 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. 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 ‘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: Nested arrays or deeper object references however require the complex curly string expression 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. 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. 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. 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: While this can also lead to syntax confusion, all better IDEs/editors again help by colorizing the escaped quotes differently. Missing opening quote Here the ‘, ‘ would become a string literal after a bareword, when obviously login was meant to be a string parameter. Array lists If you miss a , comma in an array creation block, the parser will see two consecutive strings: 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. Function parameter lists 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. HEREDOC indentation Prior PHP 7.3, the heredoc string end delimiter can’t be prefixed with spaces: 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. 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: 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: 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 Unclosed strings It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an 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<-code-6>t what PHP expects: 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. 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: 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. 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: Share solution ↓ Additional Information: Didn’t find the answer? Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free. Similar questions Find the answer in similar questions on our website. Write quick answer Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger. About the technologies asked in this question PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license. https://www.php.net/ Laravel Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework. https://laravel.com/ JavaScript JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet. https://www.javascript.com/ MySQL DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information. https://www.mysql.com/ HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone. https://www.w3.org/html/ Welcome to programmierfrage.com programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration. Get answers to specific questions Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve. Help Others Solve Their Issues Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge. Источник
  19. Missing semicolon
  20. String concatenation
  21. Missing expression operators
  22. Lists
  23. Class declarations
  24. Variables after ident<-code-19>iers
  25. Missing parentheses after language constructs
  26. Else does not expect conditions
  27. Need brackets <-code-14<-code-16>closure
  28. Invisible whitespace
  29. See also
  30. Answer
  31. Solution:
  32. Unexpected T_CONSTANT_ENCAPSED_STRING Unexpected T_ENCAPSED_AND_WHITESPACE
  33. Incorrect variable interpolation
  34. Missing concatenation
  35. Confusing string quote enclosures
  36. Missing opening quote
  37. Array lists
  38. Function parameter lists
  39. Runaway strings
  40. HEREDOC indentation
  41. Answer
  42. Solution:
  43. Unexpected
  44. Misquoted strings
  45. Unclosed strings
  46. Non-programming string quotes
  47. The missing semicolon <-code-29>again
  48. Short open tags and <-code-23>headers in PHP scripts
  49. Share solution ↓
  50. Additional Information:
  51. Didn’t find the answer?
  52. Similar questions
  53. Write quick answer
  54. About the technologies asked in this question
  55. Laravel
  56. JavaScript
  57. MySQL
  58. Welcome to programmierfrage.com
  59. Get answers to specific questions
  60. Help Others Solve Their Issues

parsing — 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 ‘<-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:

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 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.

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.

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 <-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.

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 <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> semicolons are missing at the previous line ends/statement. (At least from the stylistic viewpoint. )

If <-code-18>-code-4<-code-18>-code-5> code blocks <-code-18>-code-5> are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simpl<-code-18>-code-11>y that.

Look at the syntax colorization!

Strings and variables and constants should all have d<-code-18>-code-11>ferent colors.

Operators <-code-18>-code-6> 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 <-code-18>-code-7> or <-code-18>-code-8> string marker.

Having two same-colored punctuation characters next to each other can also mean trouble. Usually, operators are lone <-code-18>-code-11> it<-code-18>-code-8>s not <-code-18>-code-9> , <-code-18>-code-10> , or parentheses following an operator. Two strings/ident<-code-18>-code-11>iers 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 <-code-18>-code-11> statements into distinct or nested <-code-18>-code-11> conditions.

Instead of lengthy math formulas or logic chains, use temporary variables to simpl<-code-18>-code-11>y the code. (More readable = fewer errors.)

Add newlines between:

  1. The code you can easily ident<-code-18>-code-11>y as correct,
  2. The parts you<-code-18>-code-8>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<-code-18>-code-8>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<-code-18>-code-8>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 <-code-18>-code-13> condition operator can compact code and is useful indeed. But it doesn<-code-18>-code-8>t aid readability in all cases. Prefer plain <-code-18>-code-11> statements while unversed.

PHP<-code-18>-code-8>s alternative syntax ( <-code-18>-code-11>: / else<-code-18>-code-11>: / end<-code-18>-code-11><-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> ) is common for templates, but arguably less easy to follow than normal <-code-18>-code-4<-code-18>-code-5> code <-code-18>-code-5> blocks.

The most prevalent newcomer mistakes are:

Missing semicolons <-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for terminating statements/lines.

Mismatched string quotes for <-code-18>-code-7> or <-code-18>-code-8> 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<-code-18>-code-8>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<-code-18>-code-8>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, <-code-18>-code-11> you can<-code-18>-code-8>t fix it.

  • Adopt a source code versioning system. You can always view a d<-code-18>-code-11>f 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 d<-code-18>-code-11>ferent editor/viewer on your source. Some problems cannot be found just from looking at your code.

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&nbsp<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> 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

&lt<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5>?php phpinfo()<-code-18>-code-4<-code-18>-code-5>-code-1<-code-18>-code-5> for the one invoked through the webserver.

Those aren<-code-18>-code-8>t necessarily the same. In particular when working with frameworks, you will them to match up.

Don<-code-18>-code-8>t use PHP<-code-18>-code-8>s reserved keywords as ident<-code-18>-code-11>iers 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<-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.

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

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 :

Then invoke the failing code by accessing this wrapper script.

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):

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> .

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

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.

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:

Confusing <-code-11>-code-1> with opening curly braces <-code-11>or parentheses <-code-12>is a common oversight.

Or trying to dereference <-code-16>ants <-code-12>before PHP 5.6 <-code-23>as arrays:

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:

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:

Or trying to end an array where there isn’t one:

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

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

An &quot<-code-13<-code-16>unexpected <-code-1<-code-16>&quot <-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

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:

String concatenation

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

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

Missing expression operators

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

PHP can’t guess here <-code-19>the variable should have been added <-code-8<-code-16>subtracted or compared etc

Lists

Or functions parameter <-code-11<-code-16>s:

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:

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

Variables after ident<-code-19>iers

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

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:

Solution: add the missing opening <-code-23>between statement and variable

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

Else does not expect conditions

Solution: Remove the conditions from else or use

Need brackets <-code-14<-code-16>closure

Solution: Add brackets around $var

Invisible whitespace

As mentioned in the reference answer on &quot<-code-13<-code-16>Invisible stray Unicode&quot <-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:

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

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.

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 ‘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:

Nested arrays or deeper object references however require the complex curly string expression 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.

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.

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.

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:

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

Missing opening quote

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

Array lists

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

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.

Function parameter lists

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.

HEREDOC indentation

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

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.

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:

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:

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

Unclosed strings

It<-code-6>s not just literal s which the parser may protest then. Another frequent variation is an 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<-code-6>t what PHP expects:

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.

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:

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.

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:

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

Laravel

Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/

JavaScript

JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/

MySQL

DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL. It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/

HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet. Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

За последние 24 часа нас посетили 11584 программиста и 1164 робота. Сейчас ищут 309 программистов …


  1. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    Подскажите как исправить

    <?php

    require_once ‘db.php’;

    $Login = $_POST[‘login’];
    $Group = $_POST[‘Group’];
    $FIO = $_POST[‘FIO’];

    mysqli_query($connect, query: «INSERT INTO `users` (`Login`, `Group`, `FIO`) VALUES (‘$Login’, ‘$Group’, ‘$FIO’)»);
    ?>

    Parse error: syntax error, unexpected ‘:’, expecting ‘,’ or ‘)’ in W:domainsPhptestcsscreate.php on line 9


  2. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    А откуда такой синтаксис взялся, с query:? То, что новые штормы так автоматом показывают бледным шрифтом, не означает, что это так писать надо.
    — Добавлено —
    Так можно, вроде, будет писать в 8 версии php, но она пока только RC, выйдет через месяц


  3. ADSoft

    перевести трудно? гугл транслейт хотя бы?
    посмотреть описание функции?

    : — замените на ,


  4. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    заменил и и вот опять ошибка «Warning: mysqli_query() expects parameter 1 to be mysqli, null given in W:domainsPhptestcsscreate.php on line 9»


  5. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0


  6. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    Ошибка изменилась, значит проблема другая. Скорее всего, подключения к базе не произошло, судя по тексту. Или переменная не так называется. Всё написано нормальным английским языком.Не понятен вопрос. Напишите в соответствии с синтаксисом php. Если не знаете синтаксис — какого фига лезете программировать?


  7. Dimon2x

    С нами с:
    26 фев 2012
    Сообщения:
    2.176
    Симпатии:
    180

    Начни с линухи и ангийского, без этих знаний будут постоянные проблемы, на решения которых ты будешь тратить целые дни.

    PHP тащит за собой сервер, сервер тащит за собой линукс, линукс тащит за собой английский, php ничего не знает про mysql.

    PHP это язык программирования, программирование это инженерия, инжеру надо знать очень много.


    Taktreba и mkramer нравится это.


  8. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    @Dimon2x Только я бы сказал, php — это программирование, программирование тащит за собой английский


  9. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    я не понимаю почему не произошло подключения
    этот код мне выводит дание из бд
    <? include_once(‘db.php’) ?>
    <? $sql = $db->query(«SELECT * FROM `Users`»); /* запрос сам*/
    $db-> close;
    while ($result = $sql ->fetch_assoc()):?>
    <div class=»login»><h3><?=$result[‘login’] ?></h3> </div>
    <div class=»FIO»> <?=$result[‘FIO’] ?> </div>
    <? endwhile ?>

    а вот:
    не хочет вносить но подключаю к db.php
    <?php

    require_once ‘db.php’;

    $Login = $_POST[‘login’];
    $Group = $_POST[‘Group’];
    $FIO = $_POST[‘FIO’];

    mysqli_query($connect, query, «INSERT INTO `users` (`Login`, `Group`, `FIO`) VALUES (‘$Login’, ‘$Group’, ‘$FIO’)»);
    ?>


  10. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    А что в db.php? И прочитайте в подписи, как оформлять код

    Это бред сивой кобылы, прочитайте документацию по mysqli.

    И судя по коду, вы в основах путаетесь, что такое переменная, что такое параметры.


  11. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    В db.php:
    <?php
    $db = new mysqli(‘localhost’,’root’,’root’,’Users’);

    ?>


  12. acho

    acho
    Активный пользователь

    И не надо смешивать процедурный и ООП стили.


  13. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    @nevidomo, ну я же говорю, переменные не понимаете. В одном месте она у вас $db называется, а в другом месте должна как-то преобразоваться в $connect сама собой?


  14. Dimon2x

    С нами с:
    26 фев 2012
    Сообщения:
    2.176
    Симпатии:
    180

    ‘Users’ — это строка
    $users — это переменная


  15. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    зделал
    db.php:
    <?php
    $connect = new mysqli(‘localhost’,’root’,’root’,’Users’); /* connect db */

    ?>
    create.php:

    <?php

    require_once ‘db.php’;

    $Login = $_POST[‘Login’];
    $Group = $_POST[‘Group’];
    $FIO = $_POST[‘FIO’];

    mysqli_query($connect, query, «INSERT INTO `users` (`Login`, `Group`, `FIO`) VALUES (‘$Login’, ‘$Group’, ‘$FIO’)»);
    ?>
    но ошибка: Warning: mysqli_query() expects parameter 3 to be integer, string given in W:domainsPhptestcsscreate.php on line 9


  16. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    Ну уже изменилось. Но документацию по mysqli_query так и не поискал. И код оформляешь как попало. Как правильно — у меня в подписи.

    https://www.php.net/manual/ru/mysqli.query.php — читаем здесь, как правильно. Вообще не понимаю, откуда у тебя слово query в параметрах. Это неосознанное программирование, бич молодых программистов, судя по тем, что к нам на собеседования приходят. Код через сознание не проходит, спрашиваешь: «с какой целью написал именно так, а не иначе» — ответить не могут. Не приучайте себя к такому. Правило очень простое, чтоб программирование было осознанным — читать про каждую функцию, которая вызывается, документацию. Читать, как работает язык на котором пишешь. Читать, читать и ещё раз читать.


  17. nevidomo

    С нами с:
    23 окт 2020
    Сообщения:
    14
    Симпатии:
    0

    большое спасибо
    уже понял где проблема


  18. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.562
    Симпатии:
    1.284
    Адрес:
    Лень

    @nevidomo, самое начало, от чего нужно начинать отталкиваться, это

    russkij_jazyk_uchebniki_3_4_kl_1979_80_g_g.jpg

    Пи3дец — даже подсветку текстаАрены нахрен продуплить o_O какое б… программирование ??

    Читаем Parse error — что за херня ? Транслятор нельзя было врубить и перевести ??? «Ошибка синтаксического анализа»

    Что такое СИНТАКСИС ? Снова гуглим — узнаем.. Это тоже 6лядь как русский язык ГРА МА ТИ КА
    С таким же успехом дальше переводим, думаем, покурим и снова думаем, можешь даже поужинать если до такого дошло.
    Line ? строка
    Что — то в строке 9 Синтаксис долбаный сломан в PHP o_O Ведь пхп интерпретатор ругается
    Смотрим и дуплим, что там за 9 строка

    1. mysqli_query($connect, query: «INSERT INTO `users` (`Login`, `Group`, `FIO`) VALUES (‘$Login‘, ‘$Group‘, ‘$FIO‘)»);

    Идем, смотрим ОФФ документацию — гуглим mysqli_query
    Читаем и просвещаемся. Cмотрим на ПРИМЕРЫ ЗАПОЛНЕНИЯ АТРИБУТОВ, у данной функции.

    Оказывается, какого }{Yя у тебя бичь в виде «query: » скопирована из помойной документации в интернете.

    На будущее, юзай редактор с ПОДСВЕТКОЙ PHP
    — Добавлено —
    Даже тут херня эта подсвечивается

Я пытаюсь создать Reddit бота в Голанге, используя эту библиотеку, и Голанг просит запятая, однако, когда я ставлю его там, Go выдает другие ошибки.

Вот мой main.go:

package main

import (
  "github.com/turnage/graw/reddit"
)

func main() {
  cfg := BotConfig{
    Agent: "graw:doc_demo_bot:0.3.1 by /u/yourusername",
    // Your registered app info from following:
    // https://github.com/reddit/reddit/wiki/OAuth2
    App: App{
      ID:     "sdf09ofnsdf",
      Secret: "skldjnfksjdnf",
      Username: "yourbotusername",
      Password: "yourbotspassword",
    }
  }
  bot, _ := NewBot(cfg)
  bot.SendMessage("roxven", "Thanks for making this Reddit API!", "It's ok.")
}

Вот вывод с кодом выше (без запятой в 17: 7):

# command-line-arguments
./main.go:17:6: syntax error: unexpected newline, expecting comma or }

Вот вывод, когда я ставлю запятую там:

# command-line-arguments
./main.go:4:3: imported and not used: "github.com/turnage/graw/reddit"
./main.go:8:10: undefined: BotConfig
./main.go:19:13: undefined: NewBot

Я также попытался поставить запятую после строки 16 (чтобы их было две), и я получаю эту ошибку:

# command-line-arguments
./main.go:16:36: syntax error: unexpected comma, expecting expression
./main.go:17:6: syntax error: unexpected newline, expecting comma or }

Я не уверен, что делаю не так.

2 ответа

Лучший ответ

Ваши ошибки (после исправления синтаксической проблемы путем добавления запятой) все связаны друг с другом. Как написано, вы не используете пакет, который вы импортировали. Используйте reddit.BotConfig, reddit.App и reddit.NewBot для использования структур и функций из этого пакета. Импорт в Go не переносит вещи в глобальное пространство имен верхнего уровня.

func main() {
    cfg := reddit.BotConfig{
        Agent: "graw:doc_demo_bot:0.3.1 by /u/yourusername",
        // Your registered app info from following:
        // https://github.com/reddit/reddit/wiki/OAuth2
        App: reddit.App{
            ID:       "sdf09ofnsdf",
            Secret:   "skldjnfksjdnf",
            Username: "yourbotusername",
            Password: "yourbotspassword",
        },
    }
    bot, _ := reddit.NewBot(cfg)
    bot.SendMessage("roxven", "Thanks for making this Reddit API!", "It's ok.")
}


2

Darshan Rivka Whittle
22 Мар 2019 в 22:11

Вы можете поставить , после

App: App{
  ID:     "sdf09ofnsdf",
  Secret: "skldjnfksjdnf",
  Username: "yourbotusername",
  Password: "yourbotspassword",
}, //like this

Другие ошибки — это ошибки, которые вам нужно исправить. Golang является строгим и не допустит неиспользуемого импорта или неиспользуемых переменных. Также вы должны импортировать пакеты, которые содержат определения используемых вами структур — BotConfig и NewBot.

Вы можете назвать ваши импорты, чтобы вы могли ссылаться на ваш импорт без необходимости делать reddit.BotConfig. Для бывших

import r "github.com/turnage/graw/reddit"

Это позволит вам просто использовать r.BotConfig в качестве примера. В противном случае каждый раз, когда вы захотите использовать BotConfig, вам придется ссылаться на имя пакета как reddit.BotConfig


1

perennial_noob
22 Мар 2019 в 22:15

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected expecting end of file перевод
  • Syntax error unexpected eof while parsing python
  • Syntax error unexpected eof php
  • Syntax error unexpected eof expecting
  • Syntax error unexpected endforeach