Syntax error unexpected expecting yii

Примерно вот так нужно было показать схему БД. Чтобы понимать как у тебя связаны таблицы между собой.

Примерно вот так нужно было показать схему БД. Чтобы понимать как у тебя связаны таблицы между собой.
Изображение

А то, что у тебя во всех таблицах есть user_id это не беда. Беда в простом понимании связей между таблицами.
Легче же соображать, когда у тебя связь между HistoryBalance и (Person / User) прописана вот так.
Модель HistoryBalance и две примерные связи

Код: Выделить всё

public function getUser() {
        return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}
public function getPerson() {
        return $this->hasOne(Person::className(), ['person_id' => 'person_id']);
}

Т.е. у тебя в модели HistoryBalance сохраняется user_id или person_id для связи с пользователем/человеком.

Внутри модели User связь с HistoryBalance

Код: Выделить всё

public function getHistoryBalance() {
        return $this->hasMany(HistoryBalance::className(), ['user_id' => 'user_id']);
}

Внутри модели Person связь с HistoryBalance

Код: Выделить всё

public function getHistoryBalance() {
        return $this->hasMany(HistoryBalance::className(), ['person_id' => 'person_id']);
}

Для того, чтобы можно было выбрать всю историю баланса Person или User.

Тебе бы переделать БД по хорошему. Переделать первичные ключи в соответствии с названием таблицы, т.е. таблица User PK (primary key — первичный ключ) — user_id, таблица Person PK — person_id, таблица HistoryBalance PK — historybalance_id. Переделать связи в моделях.
А то в скором времени у тебя будут не очень приятные запросы в твоих search.

Твоя первоначальная задача решается несколькими путями, первый и самый простой чтобы проверить будет ли у тебя выводить информацию сделали через findHistoryBalanceByUser($id) в модели HistoryBalance.
1. делается find() из HistoryBalance
2. указывается joinWith(‘person’, false, ‘LEFT JOIN’) с таблицей пользователя (ты ведь открыл Person — View, а там в $model->id указан id пользователя из модели Person)
3. указывается условие where([‘person_id’ => $id]), говорит о том, что нужно выбрать все записи с конкретным пользователем.
4. указывается сортировка orderBy
5. устанавливается лимит limit(30)
6. т.к. возврат записей, то прописываем all(), если бы возвращался запрос то ничего не прописывали бы.

Более долгий, но всё равно нужно правильная база данных.
Берем HistoryBalanceSearch в search дописываем дополнительный параметр $id.
Примерно вот так в PersonController

Код: Выделить всё

public function actionView($id)
    {
        $model = $this->findModel($id)// поиск твоей модели
        $searchModel  = new  HistoryBalanceSearch;
	$dataProvider = $searchModel->search(Yii::$app->getRequest()->get(), $id);

        return $this->render('view', [
            'model' => $model,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

Внутри модели HistoryBalanceSearch было бы

Код: Выделить всё

public function search($params, $id = 0)
    {
        $query = HistoryBalance::find();

	if(0 < $id){
	$query
	->joinWith('person', false, 'LEFT JOIN')
	->where(['person_id' => $id])
	->orderBy(['historybalance_id' => SORT_DESC])
	->limit(30);
	}
	
        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'user_id' => $this->user_id,
            'balance' => $this->balance,
            'credit' => $this->credit,
            'balance_up' => $this->balance_up,
            'credit_up' => $this->credit_up,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['ilike', 'type', $this->type])
            ->andFilterWhere(['ilike', 'comment', $this->comment]);

        return $dataProvider;
    }

А дальше как я говорил с ListView

Код: Выделить всё

<?= ListView::widget([
	'dataProvider' => $dataProvider,
	'pager' => [
		'hideOnSinglePage' => true,
		'firstPageLabel' => Yii::t('main', 'First'),
		'lastPageLabel'  => Yii::t('main', 'Last'),
	],
	'itemView' => '_history_balance',
	'layout' => '<div class="box box-solid"><div class="box-header"><div class="pull-right">{summary}</div></div></div><div class="row">{items}</div>{pager}',
])?>

Создаешь своё представление (файл view со своими примерным именем _history_balance.php) в котором у тебя будет отрисовка информации, которая будет приходить по от контроллера $dataProvider.
Вроде бы понятно объяснил. Спрашивай конкретные вопросы, что не понял.

Содержание

  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.

Источник

Содержание

  1. Yii Framework
  2. ParseError syntax error, unexpected ‘;’, expecting ‘]’
  3. ParseError syntax error, unexpected ‘;’, expecting ‘]’
  4. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  5. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  6. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  7. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  8. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  9. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  10. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  11. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  12. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  13. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  14. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  15. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  16. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  17. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  18. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  19. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  20. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  21. Yii Framework
  22. ParseError syntax error, unexpected ‘;’, expecting ‘]’
  23. ParseError syntax error, unexpected ‘;’, expecting ‘]’
  24. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  25. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  26. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  27. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  28. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  29. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  30. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  31. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  32. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  33. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  34. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  35. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  36. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  37. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  38. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  39. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  40. Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’
  41. GoLang Tutorials
  42. Saturday, May 21, 2011
  43. Early syntax errors and other minor errors
  44. Unncessary Imports
  45. Exact Names — case dependent
  46. Separating lines with semicolons
  47. Unnecessary semicolons
  48. Syntax and other things
  49. Parse error Ошибка в шаблоне

Yii Framework

ParseError syntax error, unexpected ‘;’, expecting ‘]’

ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 12:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 13:04

Держи
ListView

И у тебя ошибка в try-catch. Посмотри все скобки и ;

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 14:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 15:45

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:47

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:04

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:12

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:38

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 17:19

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 22:46

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение yiiliveext » 2019.12.20, 22:53

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:26

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:28

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.21, 13:52

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.22, 10:33

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.22, 16:40

Можно просто сделать выборку запросом и во view сделать foreach() для простого вывода информации. А не заморачиваться с ListView

Источник

Yii Framework

ParseError syntax error, unexpected ‘;’, expecting ‘]’

ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 12:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 13:04

Держи
ListView

И у тебя ошибка в try-catch. Посмотри все скобки и ;

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 14:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 15:45

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:47

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:04

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:12

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:38

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 17:19

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 22:46

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение yiiliveext » 2019.12.20, 22:53

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:26

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:28

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.21, 13:52

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.22, 10:33

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.22, 16:40

Можно просто сделать выборку запросом и во view сделать foreach() для простого вывода информации. А не заморачиваться с ListView

Источник

GoLang Tutorials

Saturday, May 21, 2011

Early syntax errors and other minor errors

Sometimes we know what works right, but we don’t know what works wrong. Let me make a list of a few errors that one could encounter so that you don’t waste much time figuring it out.

Unncessary Imports

Copy the code below into a file and execute it.

Full file: ErrProg1.go

Go is particularly parsimonious when it comes to code — if you are not going to use something, don’t ask for it. Here, you have indicated that you want to import the os package but you haven’t used it anywhere. That’s not allowed. If you are not using it, remove it. If you remove the import os at line 4, this program will work.

Exact Names — case dependent

Full file: ErrProg2.go

Notice how we have written fmt.println and not fmt.Println. Go is case dependent, which means to say that when you use another’s name, use it exactly as it is defined. If the name is John, then only John works — not john, not joHn, and no other combination. So, in this case some of the others that are not allowed:

Separating lines with semicolons

If you are coming from a background in languages like C, C++, Java, Perl, etc. you will notice that Go (at least so far) has not required you to put semi colons at the end of the line. In Go, the new line character automatically indicates the end of the line. However, if you happen to put two statements in the same line, then you need to have a semicolon separating them. Let’s take a look at an example.

Full file: ErrProg3.go

Now you could make this work by putting the two Println statements on two separate lines, like so:

But for the purpose of illustrating this example, try out this version.

So, semi colons in Go can be used but are not compulsory on every line. But if you are going to have multiple statements in a line, you need to separate them with semi colons.

So this one is also valid and will get you the same output.
Full file: ErrProg4.go

But watch out where you go with all those free semicolons.

Unnecessary semicolons

Let’s simplify that program, but go overboard with our semicolons. Try out this code now.

Again, Go is strictly frugal with its code. Here, alongside the import statement, there are two semicolons. Now the first one is acceptable — not necessary here, but acceptable. But two! Nope, that is where Go draws the line. The semicolon indicates the end of a statement, but there is no valid statement prior to the second semicolon. So remove the extra semicolon and all should be fine again.

Syntax and other things

The compiler demands that you follow proper syntax. There are a large possibility of syntax errors and it wouldn’t be a good idea to list them all. But I shall list a few. If you know these ones, most of the rest are just similar.

Источник

Parse error Ошибка в шаблоне

Цитата
На битриксе стоит 2 сайта, на одном шаблон работает, на другом выдает такую ошибку:
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /home/www/z70998/htdocs/request/index.php on line 36
Кто может помочь?

У меня такая же ошибка
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /www/mfpaon01/www/htdocs/bitrix/templates/MFPA-ONLINE/components/bitrix/news/mfnews/detail.php on line 116

Что можно сделать?

Цитата
MiG-Z пишет:
У меня такая же ошибка

Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’ in /www/mfpaon01/www/htdocs/bitrix/templates/MFPA-ONLINE/components/bitrix/news/mfnews/detail.php on line 116

Что можно сделать?

Вот такая ошибка
Parse error: parse error, unexpected T_CONSTANT_ENCAPSED_STRING in z:home172.22.48.26wwworiflameconfig.php on line 2

скобки и апострофы вроде все проверил,все на месте. В чем проблема?? помогите! кидаю сам файл конфиг!

Цитата
/home/i/ingsystem/public_html/services/faq/index.php

Господа, таже проблема, но псле преноса сайта на агаву.
Выдает:
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘>’ in /home/polusdm1/public_html/bitrix/modules/main/include.php on line 1

Добрый день!
После обновлений не могу зайти в админку: Parse error: syntax error, unexpected ‘

Может кто нибудь помочь? Спасибо!

На перво странице сайта пишет: Parse error: syntax error, unexpected T_ELSE in /home/bitrix/www/index.php on line 25
Помогите понять где закралась оибка и как её исправить?

Содержимое файла SetTitle(«Ваша корзина»);
>else <
$APPLICATION->SetTitle(«Заказ оформлен»);

Источник

Yii Framework

ParseError syntax error, unexpected ‘;’, expecting ‘]’

ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 12:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 13:04

Держи
ListView

И у тебя ошибка в try-catch. Посмотри все скобки и ;

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 14:59

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 15:45

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:47

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 15:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:04

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:12

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.20, 16:38

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 16:49

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 17:19

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.20, 22:46

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение yiiliveext » 2019.12.20, 22:53

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:26

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.21, 12:28

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.21, 13:52

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение cqfmkapb » 2019.12.22, 10:33

Re: ParseError syntax error, unexpected ‘;’, expecting ‘]’

Сообщение unknownby » 2019.12.22, 16:40

Можно просто сделать выборку запросом и во view сделать foreach() для простого вывода информации. А не заморачиваться с ListView

Источник

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:

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.

Источник

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected expecting name
  • Syntax error unexpected expecting expression
  • Syntax error insert to complete methodbody
  • Syntax error unexpected expecting end of input
  • Syntax error unexpected expecting end of file перевод