Syntax error unexpected t boolean or

несколько условий - ошибка! Выдается ошибка: Parse error: syntax error, unexpected T_BOOLEAN_OR in 2 Строка №2: if (!isset ($POST['t'])) || (!is_numeric($POST['t'])) || ($POST['t']20) Условие должно проверять: "если не установлена t или t не число, или t меньше 1, или t больше 20"...

  • #1

несколько условий — ошибка!

Выдается ошибка:

Parse error: syntax error, unexpected T_BOOLEAN_OR in 2

Строка №2:

if (!isset ($POST[‘t’])) || (!is_numeric($POST[‘t’])) || ($POST[‘t’]<1) || ($POST[‘t’]>20)

Условие должно проверять: «если не установлена t или t не число, или t меньше 1, или t больше 20».
Что не так?

  • #2

PHP:

if ((!isset ($POST['t'])) || (!is_numeric($POST['t'])) || ($POST['t']<1) || ($POST['t']>20))

  • #4

Re: несколько условий — ошибка!

Автор оригинала: greenbegin
Что не так?

Тебе же написали!

Parse error: syntax error…

  • #5

Скобки, мля, проверь ;)

  • #6

Здесь не только синтаксическая ошибка, но и логическая ;)

  • #7

Логической ошибки нет, так как стоит ИЛИ
Только вот массив $POST уж больно на другой известный масив смахивает.
А проблемы были в скобках, что Coffin культурно поправил

c0dex


  • #8

там половина скобок только мешает ясно код видеть, и массив какой-то странный)

Условие проверки странное. Можно поподробнее что это?

  • #9

это очень похоже на постраничный вывод (правда проверка хилая).
Типа если ничего не получается — то выводим по умолчанию, иначи выводим странице от 1 до 20. Что-то типа того, но это всего лишь предположение

  • #10

Начет скобок: я просто думал что нужно брать КАЖДОЕ условие в скобки, а оказалось, что все вместе.
Начет назначения проверки: нет, это не постраничный вывод.
Всем спасибо, тему можно закрывать

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

Страница 1 из 2


  1. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    Всем привет! Посмотрите пожалуйста простой код вывода таблицы из БД по ID. Перерыл пол интернета, вроде все правильно. Но вылетает ошибка!
    Parse error: syntax error, unexpected T_BOOLEAN_OR in check.php on line 49

    1. $sql=» SELECT * FROM nn2_testing WHERE id = ‘».$q.«‘ «;
    2.     echo «<td>» . $row[‘id’] . «</td>»;
    3.     echo «<td>» . $row[‘name’] . «</td>»;
    4.     echo «<td>» . $row[‘cat2’] . «</td>»;
    5.     echo «<td>» . $row[‘price’] . «</td>»;


  2. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    while($row = mysqli_fetch_array($result)) || die(mysql_error()) { — вот эта конструкция не соответствует синтаксису пхп.


  3. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    Что нужно изменить? и на что?


  4. igordata

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

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    это зависит от того, что ты хочешь получить =)


  5. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    а что делает эта конструкция в твоем понимании?


  6. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    Я хочу получить данные из таблицы по определенному ID.
    А вообще надо так:
    Сначала вывожу всю таблицу из БД , потом нажимаю на какой нибудь ID и меняю у этой строки значение Price. Записываю обратно в базу.

    Если можно ссылки тут кидать могу кинуть на материал откуда я это взял


  7. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    слава яйцам ты мне войну и мир не процитировал.
    я не получил ответа на свой вопрос.
    я повторю вопрос:

    а что делает эта конструкция в твоем понимании?


  8. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    выводит цикл значений из БД

    Это кусок где я нажал уже на ID и дальше хочу изменить поля, но не вижу полей))


  9. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    а что такое цикл значений?
    продолжай гадать. ты написал за каким-то фигом это вот так значит ты знаешь зачем ты написал вот так и какая логика у этого алгоритма. я не прошу мне про циклы в базе данных рассказать. я прошу рассказать мне что эта конструкция делает. видишь там ключевое слово есть, знаки равенства, двойной пайп, скобочки разные. вот ты эту кашу взял и объединил в конструкцию. КАКАЯ ЛОГИКА У ЭТОЙ КОНСТРУКЦИИ? пхп тебе уже сказал что так не бывает но мне интересно знать зачем ты так написал.


  10. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    ААА понял) т.е || die(mysql_error())

    Без этого тоже не работает)
    А мож все таки ссылочку кинуть)


  11. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    но без этого и не выдаешь ошибку синтаксиса, верно?


  12. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    Warning: mysql_select_db() expects parameter 1 to be string, resource given in check.php on line 53

    Warning: mysql_query() expects parameter 1 to be string, resource given in check.php on line 60

    Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in check.php on line 69

    Синтаксиса нет, а три других да

    Добавлено спустя 2 минуты 36 секунд:
    mysql_select_db($con,’nn2_testing’); —-53
    $result = mysql_query($con,$sql); ——60
    while($row = mysql_fetch_array($result)) { ——69


  13. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    ты путаешь синтаксис mysqli и mysql. рекомендую добавить по i всё же — старую библиотеку уже отпилили из пхп.


  14. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    блин. добавил и пропал конект с базой
    Warning: mysqli_connect() [function.mysqli-connect]: (42000/1044): Access denied for user

    Добавлено спустя 4 минуты 12 секунд:
    Чето намудрил конект есть) ошибок нет) вывода из базы нет(

    Но это уже радует)

    Добавлено спустя 7 минут 47 секунд:
    Походу «q» не передает, а для ajax нужны сторонние библиотеки))?????


  15. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    а как ты делаешь аякс-запрос?


  16. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    1.         document.getElementById(«txtHint»).innerHTML = «»;
    2.         if (window.XMLHttpRequest) {
    3.             // code for IE7+, Firefox, Chrome, Opera, Safari
    4.             xmlhttp = new XMLHttpRequest();
    5.             xmlhttp = new ActiveXObject(«Microsoft.XMLHTTP»);
    6.         xmlhttp.onreadystatechange = function() {
    7.             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    8.                 document.getElementById(«txtHint»).innerHTML = xmlhttp.responseText;
    9.         xmlhttp.open(«GET»,«check.php?q=»+str,true);

    Добавлено спустя 3 минуты 50 секунд:
    q как ссылка передается

    Подсказка от модератора:
    Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
    Используйте отступы в коде для форматирования текста.
    Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
    Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.


  17. artoodetoo

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

    С нами с:
    11 июн 2010
    Сообщения:
    10.827
    Симпатии:
    1.174
    Адрес:
    там-сям

    это утверждение или вопрос?

    если js таки вызвал твой php-скрипт, значит ajax работает. но если при этом $_GET[‘q’] пустой (ты проверил?), значит надо в браузере открыть консоль, поставить брейкпоинт и посмотреть что там в переменной str. ну и пройтись выше по стеку вызовов…


  18. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    Разобрался с «q» опечатка в коде была. Теперь выводит кириллицу знаками вопроса через ajax, хотя та же таблица на той же странице без ajax выводится нормально. Куда копать не пойму. Вроде везде utf8, таблица utf8 unicod ci, все PHP и Js скрипты без BOM. Первый раз такой косяк. Где еще искать кодировку?

    Добавлено спустя 33 минуты 48 секунд:
    Я так понимаю (если я правильно понимаю) дело в запросе? Можно ли прописать там кодировку??

    1.         document.getElementById(«txtHint»).innerHTML = «»;
    2.         if (window.XMLHttpRequest) {
    3.             // code for IE7+, Firefox, Chrome, Opera, Safari
    4.             xmlhttp = new XMLHttpRequest();
    5.             xmlhttp = new ActiveXObject(«Microsoft.XMLHTTP»);
    6.         xmlhttp.onreadystatechange = function() {
    7.             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    8.                 document.getElementById(«txtHint»).innerHTML = xmlhttp.responseText;
    9.         xmlhttp.open(«GET»,«check.php?q=»+str,true);

    Добавлено спустя 2 минуты 42 секунды:
    Прописал на всех страницах

    1. header(‘Content-Type: text/html; charset=utf-8’); 

    НОЛЬ ИмоЦИЙ. те же вопросикиПодсказка от модератора:
    Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
    Используйте отступы в коде для форматирования текста.
    Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
    Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.


  19. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    кодировка еще есть в настройках пхп. в настройках сервера. даже в свойствах подключаемого скрипта.


  20. artoodetoo

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

    С нами с:
    11 июн 2010
    Сообщения:
    10.827
    Симпатии:
    1.174
    Адрес:
    там-сям

    у тебя нет указания кодировки после соединения с базой.


  21. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    пробовал таклибо ошибка, либо тоже самое.

    В базе ставлю разные кодировки, на сайте все меняется а эти строки через ajax ни как не реагируют.

    Добавлено спустя 2 минуты 23 секунды:

    ни че не нашол, не разобрался , где че? у меня нет таких настроек

    Добавлено спустя 14 минут 34 секунды:
    И еще между делом вопросик:

    У меня сечас «q» передается как валуе из выпадающего списка

    1. <select name=«name_ru-RU» onchange=«showU(this.value)»>
    2.   <option value=«»>Select:</option>
    3.   <option value=«1»>a</option>
    4.   <option value=«2»>b</option>
    5.   <option value=«69»>c</option>
    6.   <option value=«22»>nn</option>

    Как правильно организовать событие на кнопку или ссылку без перезагрузки страницы??

    1. <a onclick=«showU(this.value)» value=«‘.$data[‘product_id’].'»>W</a> 

    C onclick страница перезагружается( и данные сбрасываются. Сессии не осилю сразу говорю!

    Подсказка от модератора:
    Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
    Используйте отступы в коде для форматирования текста.
    Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
    Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.


  22. Ganzal

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

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    чтоб не перезагружалась страница при выполнении стандартных действий — нужно запрещать стандартное поведение на эти действия. в соответствующих мануалах и гуглах всё есть.


  23. artoodetoo

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

    С нами с:
    11 июн 2010
    Сообщения:
    10.827
    Симпатии:
    1.174
    Адрес:
    там-сям

    Косячник косячит везде! в mysqli_query необходимо указывать параметр «соединение с базой»

    есть два одинаково вероятных варианта:
    а) данные в базе уже испорчены из-за того, что кодировка соединения не указывалась. когда ты их выводишь «нормально», они начинают выглядеть криво.
    б) временами ты пробуешь что-то изменить не там: кран открываешь на кухне, а руки подставляешь в ванной.

    не суетись, проверь всё методично и последовательно. кодировка таблицы должна быть utf8 или utf8mb4, указание кодировки в php должно делаться везде сразу после коннекта. если сейчас не так, удали данные и сделай всё правильно.

    Шпаргалка: viewtopic.php?f=20&t=56793


  24. ghostcom

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

    С нами с:
    17 фев 2016
    Сообщения:
    92
    Симпатии:
    2

    После десяти кратного добавления-удаления строки

    1. <meta httpequiv=«Content-Type» content=«text/html; charset=utf8»> 

    Все встало на свои места, в принципе конструкция осталась та же. Грешу на тире charset=utf-8

    сейчас с аяксом мучаюсь, точнее пытаюсь в него въехать)

    по поводу mysqli_query($link, «здесь текст запроса»); не понял) сейчас после запроса нет этого. Вроде работает.

    Подсказка от модератора:
    Любой код или текст конфигурации пишите между тегом [code=php] и [/code].
    Используйте отступы в коде для форматирования текста.
    Это помогает быстрее понять вас, увеличивает шанс на получение ответа.
    Что выделять? Например: PHP, HTML, CSS, JavaScript, SQL, XML, .htaccess, ini, регулярные выражения, код шаблонизаторов, любая другая разметка, результаты array/object dump и т. д.


  25. artoodetoo

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

    С нами с:
    11 июн 2010
    Сообщения:
    10.827
    Симпатии:
    1.174
    Адрес:
    там-сям

    вопросы есть?
    я не понимаю чего ты не понимаешь. всё по русски и однозначно написано.

Страница 1 из 2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

Stuartemk opened this issue

Oct 14, 2019

· 9 comments

Comments

@Stuartemk

What needs to be fixed

Update 3.9.12 to 3.10
Check again to update say to test update 3.10 to 4
Fatal error: An error has occurred.
0 syntax error, unexpected ‘||’ (T_BOOLEAN_OR)

/public_html/administrator/components/com_joomlaupdate/views/default/tmpl/default.php:67

Why this should be fixed

Error say in line 67 but its in line 65

How would you fix it

		<?php if (!isset($this->updateInfo['object']->downloadurl->_data)

Change to

		<?php if ((!isset($this->updateInfo['object']->downloadurl->_data)

Side Effects expected

@richard67

The 3.10 branch is not up to date compared to 3.9.x = staging. Normally, after each new release of 3.9.x, the staging branch is merged into the 3.10 branch. This has not happened since last release 3.9.12, and so you can’t update from 3.9.12 to 3.10. I am sure @wilsonge or @HLeithner can confirm that.

@richard67

So I would recommend to close this issue as expected behavior. @HLeithner please confirm.

@Stuartemk

So I would recommend to close this issue as expected behavior. @HLeithner please confirm.

@richard67

Thanks for your comment. Regardless, what I reported is a bug, regardless of whether it is not an update, and that the 3.10 full version is installed. The error is there in the com_joomlaupdate component, being a simple repair I found the solution and that’s why I shared it, although the solution It is simple does not mean that the error is not serious because for a single parenthesis, simply and simply the component does not work without that solution.

@HLeithner

@richard67

@HLeithner I see, but file /public_html/administrator/components/com_joomlaupdate/views/default/tmpl/default.phpin staging does not contain the error @Stuartemk mentioned above. Could you check if there has been made a change in staging which is missing yet in 3.10? Or has there been made a change in 3.10 later which will not be changed by a merge of staging into 3.10? Maybe @zero-24 could have a look on it, too, because he recently fixed the Joomla Update version checks?

Sure you are right that it is a bug in 3.10, @Stuartemk , I only want to clarify if it has been already fixed or not in staging.

@Stuartemk

@HLeithner I see, but file /public_html/administrator/components/com_joomlaupdate/views/default/tmpl/default.phpin staging does not contain the error @Stuartemk mentioned above. Could you check if there has been made a change in staging which is missing yet in 3.10? Or has there been made a change in 3.10 later which will not be changed by a merge of staging into 3.10? Maybe @zero-24 could have a look on it, too, because he recently fixed the Joomla Update version checks?

Sure you are right that it is a bug in 3.10, @Stuartemk , I only want to clarify if it has been already fixed or not in staging.

Confirmed.
I just downloaded Joomla_3.10.0-dev-Development-Full_Package.zip

I did the clean installation and just opening joomlaupdate there is the error.

Please, before dismissing a bug report and considering it as an expected behavior, just look at the code so that you notice the error, especially you lower the mood of volunteers by dismissing the reports right and left. Regards.

@HLeithner

There was a merge conflict, it’s possible that I broke it. I will check the file and create a pr later.

@richard67

@Stuartemk Sorry for misunderstanding. I did not want to dismiss, I just wanted to clarify. You know, I am only a volunteer contributor like you are, not a maintainer, so I only can say my opinion in a discussion, and like every human being I can also be wrong. That’s why I’ve pinged a maintainer to have a look on it. But now it seems it will be fixed soon, thanks for reporting the issue.

@zero-24

Elena1986

0 / 0 / 0

Регистрация: 23.01.2013

Сообщений: 30

1

23.01.2013, 00:18. Показов 5781. Ответов 2

Метки нет (Все метки)


Пожалуйста,помогите разобраться,что не так

Parse error: syntax error, unexpected T_BOOLEAN_AND in Z:homesitewwwindex.php on line 6

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
 $a = 4;
 $b = 8;
 
 if (($a > 0)||($a == 0))&&(($b > 0)||($b == 0))
 {
 echo ($a + $b);
 }
 else if 
 {
 ($a < 0)&&($b < 0)
 {
 if ($a > $b)||($a == $b)
 {echo ($a - $b );}
 else 
 {echo ($b - $a );}
 } 
 }
 else
 {echo ($a * $b);}
 
 ?>

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.01.2013, 00:18

2

fa2m

356 / 280 / 22

Регистрация: 27.08.2012

Сообщений: 855

23.01.2013, 00:43

2

PHP
1
2
3
4
5
6
7
8
9
10
11
if ($a >= 0 and $b >= 0)
       echo ($a + $b);
elseif ($a < 0)&&($b < 0)
{  
    if ($a > $b)||($a == $b)
      echo ($a - $b );
   else
      echo ($b - $a );
} 
else
echo ($a * $b);



1



KOPOJI

Почетный модератор

Эксперт HTML/CSSЭксперт PHP

16842 / 6720 / 880

Регистрация: 12.06.2012

Сообщений: 19,967

25.01.2013, 00:45

3

с условиями что-то намудрили. Если a и b больше или равно 0, обратное условие может быть только одно — они меньше нуля. И не только там..

PHP
1
2
3
4
if ($a >= 0 && $b >= 0)
    echo $a + $b;
else
    echo $a >= $b ? $a - $b : $b - $a;



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

25.01.2013, 00:45

Помогаю со студенческими работами здесь

В чем ошибка (Parse error: syntax error, unexpected ‘$i’ (T_VARIABLE), expecting ‘;’) ?
private function select($table_name,$fields,$where=&quot;&quot;,$order=&quot;&quot;,$up=true,$limit=&quot;&quot;)
{…

Ошибка — Parse error: syntax error, unexpected T_VARIABLE как исправить?
$table = ‘tp-20’
$result = mysql_query(‘SELECT * FROM `$table` ‘);

синтаксический ошибка как…

Ошибка — Parse error: syntax error, unexpected ‘case’ (T_CASE)
Parse error: syntax error, unexpected ‘case’ (T_CASE) in E:OpenServerdomainstest.ruindex.php on…

Ошибка Parse error: syntax error, unexpected ‘elseif’ (T_ELSEIF) in
Здравия, дорогие форумчане!

Имеется файл (framework.php) темы WordPress.

При работе с ним…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

Общее о синтаксических ошибках


### Заметка:

  1. Если ваш браузер отображает сообщения об ошибках, такие как «SyntaxError: illegal character», то это на самом деле связано не с PHP, а с Javascript и синтаксическими ошибками в нём

  2. Синтаксические ошибки, возникающие в коде vendor: если синтаксическая ошибка возникла после установки или обновления пакета vendor’а — это может быть связано с несовместимостью версии PHP, поэтому проверьте версию vendor’а.
    и требования к настройке вашей платформы.

  3. Используйте IDE, например PHPStorm, который всегда подскажет, что с кодом что-то не так. Обращайте внимание на подсказки:

    введите сюда описание изображения

    введите сюда описание изображения

  4. Иногда возникают ошибки из-за лишних символов в начале файла, в частности BOM. Убедитесь, что файл сохранён в UTF-8 без BOM. (если нужен именно utf8)

  5. Если ваш веб-сайт просто пустой с белым экраном, то, как правило, причиной является синтаксическая ошибка. Включите их отображение с помощью этой инструкции

### Как интерпретировать ошибки парсера

Типичное сообщение об ошибке синтаксиса:

Parse error: syntax error, unexpected T_STRING, expecting ; in file.php on line 217

(Ошибка синтаксического анализа: синтаксическая ошибка, неожиданный T_STRING, ожидалось ; в файле file.php в строке 217)

Тут указано возможное место синтаксической ошибки. См. упомянутые имя файла и номер строки.

Токен, такой как T_STRING, объясняет, какой символ синтаксический анализатор/токенизатор не смог окончательно обработать. Однако это не обязательно является причиной синтаксической ошибки. Поэтому важно изучить предыдущие строки кода. Часто синтаксические ошибки — это ошибки, произошедшие ранее. Номер строки ошибки — это именно то место, где синтаксический анализатор окончательно отказался от обработки всего этого, а не точная линия ошибки

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected T_STRING

Unexpected identifier «xxx»

Означает, что был обнаружен необработанный идентификатор. Это может быть разное: от «голых слов» до оставшихся констант или имен функций, забытых строк без кавычек или любого простого текста. Примерные проблемы:

  1. Строки с неверными кавычками

    Любая неэкранированная и случайная кавычка " или ' образует недопустимое выражение.

                  ⇓                  ⇓
    echo "<a href="http://example.com">click here</a>";
    

    В данном примере используются двойные кавычки в двойных. Это неверно. Интерпретатор «увидит» строку "<a href=" и строку ">click here</a>" (т.к. строки заключаются в кавычки), а что такое http://example.com он не поймёт.
    Важно не забывать использовать обратный слэш для экранирования " двойных кавычек или ' одинарных кавычек — в зависимости от того, что использовалось снаружи для всей строки (для ознакомления со строками). Например если снаружи двойные кавычки, то внутри проще использовать одинарные, чтобы не запутаться, либо экранировать двойную. С одинарными аналогично. Ещё проще большой текст помещать в HEREDOC или NOWDOC

  2. Незакрытые строки

    Если вы пропустите закрывающую кавычку, то синтаксическая ошибка обычно возникает позже.

                                                            ⇓   тут не закрыли и поэтому интерпретатор считает, что строка идёт дальше
     echo "Some text", $a_variable, "and some runaway string ;
     success("finished");
             ⇯ и тут закрылась..... а что такое `finished");` он не знает
    
  3. Кавычки, не связанные с программированием

    Обычно возникают, когда копируют текст из книги. Они могут выглядеть так:

    $text = ’Something something..’ + ”these ain't quotes”;
            ^---                  ^-- ^---               ^---  
    
  4. Отсутствует точка с запятой

           ⇓
    func1()
    function2();
    
  5. Невидимые символы Unicode

    Если вы получили жалобу парсера T_STRING на совершенно не вызывающий подозрений код, например:

    <?php
        print 123;
    

    Нужно взять другой текстовый редактор. Или даже hexeditor. То, что здесь выглядит как простые пробелы и символы новой строки, может содержать невидимые константы. Такое бывает в документах с кодировкой UTF-8 BOM и нужно сделать кодировку UTF-8 без BOM

  6. Заэкранированная кавычка

    Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo "Jim said "Hello""; выведет Jim said "hello". Если применить последовательность ", то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

    "C:xampphtdocs"
    

    правильно будет экранировать обратные слэши тоже:

    "C:\xampp\htdocs\"
    


Unexpected T_VARIABLE

Unexpected ‘$varname’ (T_VARIABLE)

Означает, что есть конкретная переменная с указаннымв ошибке именем, которая не вписывается в текущую структуру выражения/инструкции.

введите сюда описание изображения

Ошибки:

  1. Отсутствует точка с запятой

    Как правило пропущена точка с запятой, а на следующей строке идёт переменная:

           ⇓
    func1()
    $var = 1 + 2;     # parse error in line +2
    
  2. Неверная конкатенация строк

                                 ⇓  Пропущен знак конкатенации
    echo "Here comes the value: "  $value;
    
  3. Пропущен оператор выражения

              ⇓
    echo 4 + 7 $var;
    
  4. В перечислениях в массивах или функциях

                                          ⇓
    $var = array("1" => $val, $val2, $val3 $val4);
    
                                    ⇓
    function myfunc($param1, $param2 $param3, $param4)
    
  5. В объявлении свойств классов

    В свойства можно назначать только статические значения (которые однозначно определены), но не выражения.

     class xyz {         ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓ - это выражение, а не статическое значение. Непозволительно
         public $value = $_GET["input"];
    

    Если необходимо присвоивать переменной выражение, то это нужно делать либо в конструкторе, либо в другом каком-либо инициализирующем методе

  6. Переменные сразу после идентификаторов

                 ⇓
    $this->myFunc$VAR();
    
  7. Отсутствие скобок до/после языковых конструкций if, for, foreach

           ⇓
    foreach $array as $key) {
    
                              ⇓
    if ($var = pdo_query($sql) {
        $result = …
    
  8. Else не ожидает условий

         ⇓
    else ($var >= 0)
    

    тут надо либо фигурные скобки, либо применять elseif (если не нарушает логики)

  9. Необходимы скобки для замыканий (closure)

                   ⇓
    function() use $var {}
    

    Переменные, которые передаются в замыкания всегда надо оборачивать в круглые скобки

  10. Невидимые пробелы

    Как отмечалось ранее. Могут быть невидимые символы. Проверьте на их наличие (читайте выше ошибки Unexpected T_STRING)

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected T_CONSTANT_ENCAPSED_STRING

Unexpected T_ENCAPSED_AND_WHITESPACE

Предупреждения T_ENCAPSED… появляются в контексте строки с двойными кавычками, в то время как строки T_CONSTANT… часто возникают в простых выражениях или операторах PHP.

Ошибки:

  1. Неправильная интерполяция переменных

    echo "Here comes a $wrong['array'] access";
    

    Ключи массива должны быть в кавычках. Но в строках с двойными кавычками (или HEREDOC) это не так. Парсер жалуется на содержащуюся в одинарных кавычках строку.

    Можно использовать PHP2-style для написания ключей мамссивов внутри строки

    echo "This is only $valid[here] ...";
    

    Но лучше изучить фигурный синтаксис и использовать его. Он позволяет писать ключи массива как обычно:

    echo "Use {$array['as_usual']} with curly syntax.";
    
  2. Отсутствует конкатенация

                          ⇓
    echo "Hello " . WORLD  " !";
    
  3. Отсутствует начальная кавычка

             ⇓
    make_url(login', 'open');
    
  4. Пропущена запятая в массиве

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    
  5. Пропущена запятая в аргументах функции/метода

                              ⇓
    myfunc(123, "text", "and"   "more")
    
  6. Строка закрыта слишком поздно

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    
  7. Отступ в HEREDOC

    До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже вызовет ошибку

    $test = <<<HTML
           <link..>
       HTML;
    ⇑⇑⇑
    


Unexpected $end

Unexpected end of file

Ошибка означает, что код закончился, в то время как парсер ожидает больше кода. (Сообщение немного вводит в заблуждение, если понимать его буквально. Речь идет не о переменной с именем «$end», как иногда предполагают новички. Оно относится к «концу файла»). Причина: несовпадение количества открывающих и закрывающих фигурных скобок.

Почти всегда речь идет об отсутствующей закрывающей фигурной скобке } для закрытия предшествующих блоков кода. Это говорит о том, что синтаксический анализатор ожидает найти закрывающую скобку }, но на самом деле достиг конца файла.

  • Используйте правильные отступы, чтобы избежать таких проблем. И вообще, в принципе, используйте отступы и форматирование!
  • Используйте IDE с сопоставлением скобок, чтобы выяснить, где } была утеряна. Большинство IDE выделяют совпадающие фигурные скобки, квадратные скобки и круглые скобки. Что позволяет довольно легко проверить соответствие:

введите сюда описание изображения

Отступ в HEREDOC

До версии 7.3 закрывающий идентификатор должен был находиться в самом начале новой строки. Поэтому код ниже может вызывать ошибку

$test = <<<HTML
        <link..>
    HTML;
⇑⇑⇑ 

Заэкранированная кавычка

Символ имеет особое значение. Часто символ применяют для экранирования в строках. Чтобы кавычка внутри строки, которая обёрнута в такие же кавычки, печаталась как есть, то её экранируют. Т.е. строка echo "Jim said "Hello""; выведет Jim said "hello". Если применить последовательность ", то она будет расценена как попытка экранирования кавычки. Поэтому строка ниже, выдаст ошибку

"C:xampphtdocs"

правильно будет экранировать обратные слэши тоже:

"C:\xampp\htdocs\"

С другой стороны, PHP обычно преобразует пути в стиле Unix (например, "C:/xampp/htdocs/") в правильный путь для Windows.

Альтернативный синтаксис

Несколько реже вы можете увидеть эту синтаксическую ошибку при использовании альтернативного синтаксиса для блоков операторов/кодов в шаблонах. Используя if: и else: отсутствует endif;, например (т.е. закрывающий тег)



Unexpected T_FUNCTION

Может возникнуть например в версии PHP ниже 5.3.0, когда не было ещё анонимных функций. В некоторые функции, такие как array_map нужно было передать имя функции обработчика, например $range = array_map( "name_of_function_to_call", $myArray );. Так что минимум надо проверить версию PHP и проверить что именно на вход ожадает текущая функция. И принять решение: повысить версию PHP или переписать под старый стиль: создать отдельно функцию и во вторую передать имя первой.

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected (

Открывающие круглые скобки обычно следуют за языковыми конструкциями, такими как if/foreach/for/array/list, или начинают арифметическое выражение. Они синтаксически неверны после "strings", предыдущих скобок (), одинокого $ и в некоторых типичных контекстах объявлений. Типичные ошибки:

  1. Выражения в параметрах объявленной функции

    function calcRating($value, $expires = time() + 90000) {
    

    Параметры в объявлении функции могут быть только литеральными значениями или константными выражениями. То есть выражение time() + 90000 нельзя использовать в качестве дефолтного значения параметра функциию. Тем не менее при вызове функции можно свободно использовать выражение:

    myFunction(1 + anotherFunc() * 2)
    
  2. Выражения в свойствах класса

    Как и ошибка выше, нельзя применять выражения для свойств класса, т.е.

    class xyz {                   
        var $default = someFunction("xyz_default");
    

    Если необходимо что-то вычислить, то данные вычисления/выражения стОит помеестить в конструктор класса.

    Единственное, PHP 7 позволяет написать public $property = 1 + 2 + 3;. Но это посзволительно, т.к., по сути, это выражение с константными значениями, не вычисляемое «на лету».

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

    И isset() и empty() являются встроенными языковыми конструкциями языка, а не функциями, им необходим прямой доступ к переменной. Если вы непреднамеренно добавите слишком много скобок, то вы создадите доп. выражение:

              ⇓
    if (isset(($_GET["id"]))) {
    

    Для PHP <= 5.4 будет ошибка Parse error: syntax error, unexpected '('

    Для PHP <= 7.0 будет ошибка Fatal error: Cannot use isset() on the result of an expression

    Начиная с версии 7.0 — ошибки не будет

Unexpected )

  1. Висячая запятая при вызове функции/метода

                  ⇓
    callfunc(1, 2, );
    

    В новых версиях языка позволены висячие запятые при нициализации массивов или списков (а также в объявлении функций/методов), но не при вызове функций/методов

  2. Незавершённые выражения

    Например если забыли в арифметическом выражении, то синтаксический анализатор сдается. Потому что он не знает как интерпретировать это:

                   ⇓
    $var = 2 * (1 + );
    

    Но если забыли закрывающую скобку вдобавок, то получите жалобу о неожиданной точке с запятой.

  3. Foreach as constant

    Если забыть добавить доллар к переменной:

                       ↓    ⇓
    foreach ($array as wrong) {
    

    PHP здесь иногда говорит, что вместо этого ожидался -> или ?->. Поскольку class->variable мог бы удовлетворить ожидаемому выражению.

Unexpected {

Фигурные скобки { и } окружают блоки кода. И синтаксические ошибки о них обычно указывают на какую-то неправильную вложенность.

  1. Unmatched subexpressions in an if (Несовпадающие подвыражения) в if

    Чаще всего несбалансированные ( и ) являются причиной, если парсер жалуется на открывающуюся фигурную скобку {, которая появляется слишком рано. Простой пример:

                                 ⇓
    if (($x == $y) && (2 == true) {
    

    Необходимо посчитать все открывающие и закрывающие скобки и сопоставить их количество. Также используйте IDE, которая помогает в этом и не пишите код без пробелов. Удобочитаемость имеет значение.

  2. { and } в выражениях

    Нельзя оборачивать выражения в скобки.

               ⇓
    $var = 5 * {7 + $x};    
    

    Придётся выражение вынести в переменную и подставлять уже её:

    $expr = 7 + $x
    $var = 5 * $expr; 
    

Unexpected }

Когда получаете ошибку «unexpected }«, чаще всего означает, что закрывали блок кода слишком рано.

  1. Последнее выражение в блоке и потеря точки с запятой

    function whatever() {
        doStuff()
    }            ⇧
    
  2. Недопустимая вложенность блоков/Forgotten { (забытая { )

    Блок кода был } закрыт слишком рано, или забыли открытую скобку {:

    function doStuff() {
        if (true)    ⇦
            print "yes";
        }
    }   ⇧
    

    В приведенном выше фрагменте if не было открывающей фигурной скобки {. Таким образом, закрывающая } ниже стала излишней. И поэтому следующая закрывающая }, предназначенная для функции, не была связана с исходной открывающей фигурной скобкой {.

Unexpected {, expecting (

Языковые конструкции, требующие условия/объявления и блока кода, вызовут эту ошибку.

  1. Список параметров функции/метода

                     ⇓  нет скобок и параметров
    function whatever {
    }
    
  2. Условные конструкции

      ⇓  нельзя писать if без какого-либо условия
    if {
    }
    

То же самое для частых используемых конструкций: for/foreach, while/do, etc.

Как минимум всегда смотрите документацию, чтобы сравнить, правильно ли вы пишите ne или иную конструкцию/функцию/метод/класс и т.д.

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected [

Часто возникает в старых версиях PHP. В версии PHP >= 5.4 стал возможен сокращённый синтаксис объявления массивов

$php53 = array(1, 2, 3);  // Старый синтаксис
$php54 = [1, 2, 3];       // Новый синтаксис PHP >= 5.4
         ⇑

Разыменование массивов также с версии 5.4. Оно позволяет, например, сразу же обратиться к ключу массива, который вернула функция.

function getData() {
    return ['first' => 1, 'second' => 2];
}
getData()['first'];
         ⇑  // До версии 5.4 это невозможно
         

это же касается и встроенных функций, например explode и других, которые возвращают массив

Обязательно проверьте версию PHP


Другие варианты:

  • Нельзя в свойствах метода сразу внести данные в ячейку массива

    protected $var["x"] = "Nope";
                  ⇑⇑⇑⇑
    

    Если это необходимо — делайте это в конструкторе или каком-либо инициализирующием методе

  • Случайно опеатались и вместо другой скобки поставили квадратную

    foreach [$a as $b)
            ⇑  
    

    или даже

    function foobar[$a, $b, $c] {
                   ⇑
    
  • Вы пытаетесь использовать ключевое слово global для члена ассоциативного массива. Это недопустимый синтаксис:

    global $var['key'];
    

Unexpected ]

  • Случайно опеатались и вместо другой скобки поставили квадратную

    foreach [$a as $b)
            ⇑  
    
  • Пытаетесь закончить массив там, где его нет:

    $var = 2];
    

    Часто это возникает во вложенных массивах

    $array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
                                                 ⇑
    

    Используйте IDE для сопоставления скобок и нормально форматируйте код %))

→ Ссылка

Автор решения: Алексей Шиманский

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

Частые проблемы с операторами if, foreach, for, while, list, global, return, do, print, echo

  1. Точка с запятой не там

    Довольно часто пропущена точка с запятой в предыдущей строке

                 ⇓
    $x = myfunc()
    if (true) {
    
  2. Код в классе, находится вне методов

    class xyz {
        if (true) {}  <-- нельзя так! надо писать в методах!!!
        foreach ($var) {}  <-- нельзя так! надо писать в методах!!!
    
  3. Используются зарезервированные ключевые слова в качестве идентификаторов

    Нельзя использовать do, if и другие языковые конструкции в качестве имён функций/методов или имён классов.

  4. СтоИт точка с запятой вместо двоеточия (:) или фигурной скобки ({) после блока управления

    Управляющие структуры обычно заключены в фигурные скобки, но в альтернативном синтаксисе могут использоваться двоеточия. Если там случайно использовать точку с запятой, то преждевременно закрывается этот самый блок:

      foreach ($errors as $error); <-- должно быть  :  или  {
    


Unexpected T_LNUMBER

  1. Недопустимые имена переменных

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

     $1   // Плохо 
     $_1  // Хорошо
    

    *

    • Довольно часто появляется при использовании preg_replace-заполнителей "$1" но в контексте функций непосредственно PHP:

        #                         ↓            ⇓  ↓
        preg_replace("/#(w+)/e",  strtopupper($1) )
      

      Там, где callback — должны были быть кавычки. Однако их пропустили (P.S. флаг /e устарел, но иногда он всё еще неправильно используется в preg_replace_callback)

    • Хотя токенизатор/парсер не допускает буквального $1 в качестве имени переменной, можно использовать ${1} или ${"1"}. Это синтаксический обходной путь для нестандартных идентификаторов. (Лучше думать об этом как о поиске в локальной области. Но в целом: для таких случаев предпочитайте простые массивы!)

  2. Обращение к нумерованному ключу объекта через стрелочку ->

    Обычно возникает в объектах типа stdClass Object, появляющиеся после json_decode без флага true

                ↓
         $json->0->value
    

    Правильно будет:

                ↓↓↓
         $json->{0}->value           
    
  3. Пропущены запятые в объявлении массивов

     #            ↓ ↓
     $xy = array(1 2 3);
    

    Или подобное, но в параметрах функции или конструкций:

    func(1, 2  3);`
              ^----
    
    function xy($z 2);
                  ^-----
    
    for ($i=2 3<$z)
             ^----
    

    Обычно один из знаков, таких как ; или , пропущен при разделении списка выражений.

  4. Ошибка расстановки кавычек, несовпадение кавычек

     #                 ↓ ↓          
     echo "<td colspan="3">something bad</td>";
    

    Подробно описано про кавычки в Unexpected T_STRING errors.

  5. Другие идентификаторы

    Ни функции, ни классы, ни пространства имен не могут начинаться с числа:

              ↓
     function 123shop() {
    

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected ‘?’

Если вы пытаетесь использовать тег <?php внутри другого такого же тега <?php*

$var = 'hello '<?php echo 'world'; ?>;

* Для PHP версий 4.3.1, 4.3.5 — 4.3.11, 4.4.0 — 4.4.1, 5.0.0 — 5.0.5, 4.4.2 — 4.4.9, 5.1.0 — 5.1.6, 5.2.0 — 5.2.17, 5.3.0 — 5.3.29, 5.4.0 — 5.4.45, 5.5.0 — 5.5.38, 5.6.0 — 5.6.40, 7.0.0 — 7.0.33, 7.1.0 — 7.1.33, 7.2.0 — 7.2.34, 7.3.0 — 7.3.31, 7.4.0 — 7.4.24


Если используется оператор null coalescing operator ?? в версиях PHP ниже, чем PHP 7

<?= $a ?? 2; // Работает в PHP 7+
<?= (!empty($a)) ? $a : 2; // Работает во всех версиях PHP

Unexpected ‘?’, expecting variable

Аналогичная ошибка может возникнуть для типов, допускающих значение NULL, например:

function add(?int $sum): ?int {

Что снова указывает на то, что используется устаревшая версия PHP (то же касается CLI). Проверьте версию PHP через phpinfo();. Необходимо будет либо повысить версию, либо переписать код под старые версии, без использования нового синтаксиса



Unexpected ‘continue’ (T_CONTINUE)

Оператор continue используется только внутри циклических структур для пропуска оставшейся части текущей итерации цикла и, при соблюдении условий, начала следующей итерации. continue не возвращает значения
Таким образом continue нельзя использовать в тернарном операторе или любом операторе, требующем возвращаемого значения (return).

Unexpected ‘break’ (T_BREAK)

То же самое касаестся break;. Нельзя использовать в выражениях (те, что могут вернуть значение). Используется внутри for, foreach, while, do-while или switch.

Unexpected ‘return’ (T_RETURN)

Если на предыдущих строках произошла синтакцическая ошибка, то при приходе к слову return будет подобная ошибка. Например:

is ($value == null) { // Ожидалось что будет if    
    return $this->unban();
}

или

mysql_query("INSERT INTO 'users' VALUES ('', '$email', '$name', '".md5 ($password)."')" 
                                                                                       ^^^ нет знаков  );
return mysql_insert_id();   

При данной ошибке ищите синтаксическую ошибку раньше указанного места в тексте ошибки, а не прямо на этой же строчке.



Unexpected ‘=’

Может быть вызвано наличием недопустимых символов в имени переменной. Имена переменных должны соответствовать следующим правилам:

Имена переменных соответствуют тем же правилам, что и остальные наименования в PHP. Правильное имя переменной должно начинаться с буквы или символа подчёркивания и состоять из букв, цифр и символов подчёркивания в любом количестве. Это можно отобразить регулярным выражением: ^[a-zA-Z_x80-xff][a-zA-Z0-9_x80-xff]*$

Замечание: Под буквами здесь подразумеваются символы a-z, A-Z и байты от 128 до 255 (0x80-0xff).



Unexpected T_PAAMAYIM_NEKUDOTAYIM

T_PAAMAYIM_NEKUDOTAYIM — это наименование для двойного двоеточия :: на иврите ¯_(ツ)_/¯

Происходит использование двойного двоеточия, вместо стрелочки объекта (статический вызов, вместо вызова метода в нестатическом контексте).

Например в коде указано $cnf::getConfig($key);, а должно быть $cnf->getConfig($key);

Это было возможно в ранних версиях. Возможно ошибка появилась после переноса куда-либо (например нахостинг). Поэтому проверьте версию PHP и либо установится такую же версию, на которой было разработано приложение, либо измените вызов свойства/метода на вызов их не в статическом виде



Unexpected T_OBJECT_OPERATOR

  1. В очень старых версиях PHP (4) нельзя делать «method chaining», т.е. консрукция ниже не сработает

    $item->get_enclosure()->get_link()
    
  2. В версиях ниже *PHP 5.4* нельзя вызвать метод у только что созданного объекта

    $purchaseOrder = (new PurchaseOrderFactory)->instance();
    

    можно вначале создать объект, а только потом вызвать у него метод:

    $purchaseFactory = new PurchaseOrderFactory;
    $purchaseOrder = $purchaseFactory->instance();  
    

    Также нужно обратить внимание на круглые скобки, писать new PurchaseOrderFactory->instance(); нельзя, это невалидно!

  3. Пропущен знак доллара у переменной.

    Например написано mysqli->query, а должно быть $mysqli->query или написано this->transform($lessons) а должно быть $this->transform($lessons)



Unexpected T_DOUBLE_ARROW

Причины:

  1. Использование `=>` при описании массива, но при этом ключевое слово объявления массива было забыто:

    $statement->execute( ':login'=>$_POST['email'] );
    

    должно быть

    $statement->execute(array(':login' => $_POST['email']));
    
  2. Пропущена запятая перед объявлением массива

    Route::post('/updateaccount'[
                               ⇑  
        'uses' => '[email protected]',
        'as' => 'account.save'
    ]);
    

    должно быть

    Route::post('/updateaccount', [  
                                ⇑    
        'uses' => '[email protected]',
        'as' => 'account.save'
    ]);
    
  3. Пропущена какой-то закрывающий элемент в пересислении массива

    $saveData = array(
        'mid' => $this->_saveAsUserId,        
        'post_name' => slug($thisShow['title'],
                                              ⇑   Пропущена закрывающая скобка функции slug        
        'post_content' => $thisShow['content'],        
    );
    


Unexpected T_BOOLEAN_OR
Unexpected T_BOOLEAN_AND

Возникают, как правило, вследствие несовпадения открывающих и закрывающих круглых скобок. Пример

if(is_file($filechk1) && (is_file($filechk2))) || (is_file($dirchk1) && (is_file($dirchk2))){
                                             ⇑
    ...
}

или

if ($args == !empty && $command != 'reload'){
             ^^^^^^ Невалидно. должно быть `!empty($args)`
}

или

if(isset($_GET['test'] && strcmp($_GET['test'],'test') == 0)
                     ⇑
                     

Решение: проверьте весь код на соответствие скобок друг другу! Если нужно, то выносите сложные конструкции в отдельные переменные, чтобы не путаться и работайте с ними. Пример

if (IS_REGISTRATOR() && (($params.status === 'W' || $params.status === 'D' || $params.status === 'A') && $params.remark && (($params.subres_level == 0 && ($user_info->selected_title->tid == $params.boss || $user_info->selected_title->tid == $doc_signer_tid || !$params.usertid) || $params.subres_level > 0 && $user_info->selected_title->tid == $params.usertid))) { ... }                       

этот код будет читаться легче в таком виде:

$docIsInWorkAcceptOrDraft = ...;
$bossHasSignerPriviledge = ...;
$userCanSign = ...;

if ($docIsInWorkAcceptOrDraft && $bossHasSignerPriviledge && $userCanSign) {
  // ...
}   

→ Ссылка

Автор решения: Алексей Шиманский

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

Операторы сравнения, такие как ==, >=, ===, !=, <>, !== and <= or < and > в основном должны использоваться только в выражениях, таких как if. Если синтаксический анализатор жалуется на них, то это часто означает несовпадение в парах скобок, несоответствие скобок ( ) вокруг выражений.

  1. Группировка в выражениях

    В частности, для операторов if с множественными сравнениями, вы должны позаботиться о правильном подсчете открывающих и закрывающих скобок (!!!):

                            ⇓
    if (($foo < 7) && $bar) > 5 || $baz < 9) { ... }
                          ↑
    

    Здесь условие if случайно завершено скобкой ) и дальше парсер не понимает что происходит

  2. Смешивание isset()/empty() и сравнения

                           ⇓  пропущена закрывающая скобка
    if (empty($_POST["var"] == 1)) {
    

    Или:

                       ⇓
    if (isset($variable !== "value")) {
    

    Это не имеет смысла для PHP, потому что isset и empty — языковые конструкции, которые принимают только имена переменных. Также не имеет смысла сравнивать результат этих конструкций с чем-либо, потому что результат этих конструкций — логический.

  3. Путаница >= больше или равно с оператором массива =>

    Оба оператора выглядят примерно одинаково, поэтому их иногда путают:

             ⇓
    if ($var => 5) { ... }
    

    Нужно помнить, что этот оператор сравнения называется «больше, чем или равно» (greater than or equal), чтобы все было правильно.

  4. Не с чем сравнивать

    Нельзя объединить два сравнения, если они относятся к одной и той же переменной:

                   ⇓
    if ($xyz > 5 && < 100)
    

    Необходимо каждый раз сравнивать значение переменной:

    if ($xyz > 5 && $xyz < 100)
    
  5. Цепочки сравнения

    Также нельзя сравнивать значение переменной одновременно с несколькими значениями. В математике, например, конструкция ниже позволена:

                       ⇓
     $result = (5 < $x < 10);
    

    Однако в PHP такое не допустимо. Следует, как указано выше, сравнивать значение каждый раз, т.е.

     $result = ($x > 5 && $x < 10);
    
  6. Unexpected >
    Unexpected <

    Операторы больше > или меньше < не имеют пользовательского имени токенизатора T_XXX. Чаще всего ошибка возникает, когда не так расставлены кавычки в HTML коде:

                            ⇓
    print "<a href='z">Hello</a>";
                     ↑
    

    В текущем случае получается, что строка сравнивается через > с константой Hello и затем происходит ещё одно сравнение с помощью <. По крайней мере, так это видит PHP. Настоящей причиной и синтаксической ошибкой было преждевременное завершение строки.

    Вложенные теги также вызывают ошибку::

    <?php echo <?php my_func(); ?>
               ↑
    

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected ‘public’ (T_PUBLIC)
Unexpected ‘private’ (T_PRIVATE)
Unexpected ‘protected’ (T_PROTECTED)
Unexpected ‘final’ (T_FINAL)

Ключевые слова public/private/protected/final можно использовать только внутри класса в качестве модификатора для свойств или методов. Ключевое слово final может применяться ещё и для обозначения самого класса как финального.

Ошибка может заключаться в применении этих слов для простых функций вне класса, например

<?php 

public function echoTest() {    
    echo 'test';
}

Это неправильно! Нужно использовать только в классах!

Если же это происходит в классе, то смотрите на соответствия фигурных скобок закрывающих и открывающих — где-то может не хватать закрывающей фигурной скобки и в итоге парсер не ожидает увидеть ключевое слово.

→ Ссылка

Автор решения: Алексей Шиманский

Unexpected T_STATIC

Может возникать в классе, когда используется позднее статическое связывание через ключевое слово static

class Employee {
    public static $favSport = "Football";

    public static function watchTV() {
        echo "Watching ".static::$favSport;
    }
}

Частой причиной может быть рання версия языка. Ключевое слово появилось в версии 5.3. Возможно у вас стоИт более ранняя версия.

Также если в классе static применяется в качестве возвращаемого значения:

 public function setDefault(string $option, mixed $value): static 
 

Данное возвращаемое значение можно использовать в языке в версии 8.0+. Проверьте свою версию PHP



Unexpected T_CLASS

Может возникать в классе, когда используется позднее статическое связывание через ключевое слово [::class](https://www.php.net/manual/ru/language.oop5.basic.php#language.oop5.basic.class.class)

$kernel = $app->make(IlluminateContractsHttpKernel::class);

Частой причиной может быть рання версия языка. Ключевое слово появилось в версии 5.5. Возможно у вас стоИт более ранняя версия.

Ещё может быть случайно строка представлена константой. Пример:

$host=""MyHost"";

Тут ошибка заключается в том, что вместо того, чтобы написать одну двойнуй кавычку слева и одну справа, двойные кавычки написаны по две штуки. В итоге получается слева пустая строка и справа, а host это какая-то константа, воспринимаемая как указание на какой-то класс



Unexpected ‘use’ (T_USE)

Может возникать в классе, когда используется ключевое слово use используется для импорта класса, но используется оно не до объявления класса/функции, а внутри него. Пример:

function test() {
    use CoinbaseWalletClient;
    use CoinbaseWalletConfiguration;
    
    ...
}

Все импорты классов должны быть в самом начале файла:

<?php 

use CoinbaseWalletClient;
use CoinbaseWalletConfiguration;

class Test {
    function test() {       
        ...
        ...
    }
}

Исключение составляют трейты, которые могут использовать use внутри класса для импорта трейта (см. документацию)


Ещё проблема может возникать при использовании use для именованных функций. Это неверно! Оно может использоваться только для анонимных функций. Пример:

// НЕВЕРНО!!!
function checkValue($arrPostKey, $value) use ($errors) {
                                         ^^^^
    ...
};

// ВЕРНО
$checkValue = function($arrPostKey, $value) use (&$errors) {
    ...
}

Ещё одна проблема: в перечислении импортов сверху класса была забыта точка с запятой:

use IlluminateHttpRequest;
use Auth;
use AppTask   <-----
use AppProject;    


Unexpected T_DNUMBER

Частая проблема: использовать данные как есть, вместо оборачивания их как строки. Пример:

// НЕВЕРНО
$this->Server = mysql3.000webhost.com;  // как итог: видим 3.000 ... на что и ругается парсер.

// ВЕРНО
$this->Server = 'mysql3.000webhost.com';
                ^---                  ^---

→ Ссылка

  1. Home

  2. parsing — PHP parse/syntax errors; and how to solve them

578 votes

6 answers

Get the solution ↓↓↓

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:

  • Unexpected T_STRING

  • Unexpected T_VARIABLE

  • Unexpected T_CONSTANT_ENCAPSED_STRING

  • Unexpected $end

  • Unexpected T_FUNCTION…

  • Unexpected

  • Unexpected

  • Unexpected T_IF

  • Unexpected T_LNUMBER

  • Unexpected ?

  • Unexpected continue (T_CONTINUE)

  • Unexpected ‘=’

  • Unexpected T_INLINE_HTML…

  • Unexpected T_PAAMAYIM_NEKUDOTAYIM…

  • Unexpected T_OBJECT_OPERATOR…

  • Unexpected T_DOUBLE_ARROW…

  • Unexpected T_SL…

  • Unexpected T_BOOLEAN_OR…

    Unexpected T_BOOLEAN_AND…

  • Unexpected T_IS_EQUAL

  • Unexpected T_NS_SEPARATOR…

  • Unexpected character in input: ‘

  • Unexpected ‘public’ (T_PUBLIC) …

  • Unexpected T_STATIC…

  • Unexpected T_CLASS…

  • Unexpected ‘use’ (T_USE)

  • Unexpected T_DNUMBER

  • Unexpected (comma)

  • Unpexected (period)

  • Unexpected (semicolon)

  • Unexpected (asterisk)

  • Unexpected (colon)

  • Unexpected ‘:’, expecting ‘,’ or ‘)’

  • Unexpected (call-time pass-by-reference)

  • Unexpected

Closely related references:

  • What does this error mean in PHP? (runtime errors)
    • Parse error: syntax error, unexpected T_XXX
    • Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE
    • Parse error: syntax error, unexpected T_VARIABLE
  • What does this symbol mean in PHP? (language tokens)
  • Those

And:

  • The PHP manual on php.net and its various language tokens
  • Or Wikipedia’s syntax introduction on PHP.
  • And lastly our of course.

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.

2021-11-28

Write your answer


469

votes

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.

{-code-18}-code-7}Function

Most important tips

There are a few basic precautions you can always take:

  • Use proper code indentation, or adopt any lofty coding style.
    Readability prevents irregularities.

  • Use an with syntax highlighting.
    Which also help with parentheses/bracket balancing.

    {-code-18}-code-7}Expected:

  • 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 ad{-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.

    • Try as the first measure to find non-ASCII symbols.

    • In particular BOMs, zero-width spaces, or non-breaking spaces, and smart quotes regularly can find their way into the source code.

  • Take care of which type of linebreaks are saved in files.

    • PHP just honors n newlines, not r carriage returns.

    • Which is occasionally an issue for MacOS users (even on OS {-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

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

Further guides:

  • PHP Debugging Basics by David Sklar
  • Fixing PHP Errors by Jason McCreary
  • PHP Errors – 10 Common Mistakes by Mario Lurig
  • Common PHP Errors and Solutions
  • How to Troubleshoot and Fix your WordPress Website
  • A Guide To PHP Error Messages For Designers — Smashing Magazine

White screen of death

If your website is just blank, then typically a syntax error is the cause.
Enable their display with:

  • error_reporting = E_ALL
  • display_errors = 1

In your generally, or via for mod_php,
or even with FastCGI setups.

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, saytest.php:

<{-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}?php
   error_reporting(E_ALL){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   ini_set({-code-18}-code-7}display_errors{-code-18}-code-7}, 1){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}
   include({-code-18}-code-7}./broken-script.php{-code-18}-code-7}){-code-18}-code-4{-code-18}-code-5}-code-1{-code-18}-code-5}

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP{-code-18}-code-8}serror_log and look into your webserver{-code-18}-code-8}s when a script crashes with HTTP 500 responses.


81

votes

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

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)


20

votes

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

{-code-17}php53 = array{-code-12}1, 2, 3{-code-23};
{-code-17}php54 = {-code-11}-code-1}1, 2, 3{-code-21};
         ⇑

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

{-code-17}result = get_whatever{-code-12}{-code-23}{-code-11}-code-1}"key"{-code-21};
                      ⇑

Reference — What does this error mean in PHP? — «Syntax error, unexpected shows the most common and practical workarounds.

Though, you’re always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g.{-code-11}-code-7} can be used to enable a newer runtime.

See also:

  • PHP syntax for dereferencing function result в†’ possible as of PHP 5.4
  • PHP syntax error, unexpected ‘{-code-11}-code-1}’
  • Shorthand for arrays: is there a literal syntax like {-code-11}} or {-code-11}-code-1}{-code-21}?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘{-code-11}-code-1}’
  • PHP Difference between {-code-11}-code-3} and {-code-11}-code-1}{-code-21}
  • PHP Array Syntax Parse Error Left Square Bracket «{-code-11}-code-1}»

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:

  • You can’t use array property declarations/expressions in classes, not even in PHP 7.

    protected {-code-17}var{-code-11}-code-1}"x"{-code-21} = "Nope";
                  ⇑
    
  • Confusing{-code-11}-code-1} with opening curly braces{-code-11} or parentheses{-code-12} is a common oversight.

    foreach {-code-11}-code-1}{-code-17}a as {-code-17}b{-code-23}
            ⇑
    

    Or even:

    function foobar{-code-11}-code-1}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                   ⇑
    
  • Or trying to dereference {-code-16}ants {-code-12}before PHP 5.6{-code-23} as arrays:

    {-code-17}var = {-code-16}{-code-11}-code-1}123{-code-21};
           ⇑
    

    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:

    {-code-19} {-code-17}var{-code-11}-code-1}'key'{-code-21};
    

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:

    function foobar{-code-12}{-code-17}a, {-code-17}b, {-code-17}c{-code-21} {-code-11}
                              ⇑
    
  • Or trying to end an array where there isn’t one:

    {-code-17}var = 2{-code-21};
    

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

    {-code-17}array = {-code-11}-code-1}1,{-code-11}-code-1}2,3{-code-21},4,{-code-11}-code-1}5,6{-code-11}-code-1}7,{-code-11}-code-1}8{-code-21},{-code-11}-code-1}9,10{-code-21}{-code-21},11{-code-21},12{-code-21}{-code-21},15{-code-21};
                                                 ⇑
    

    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.


146

votes

Answer

Solution:

Unexpected {-code-1{-code-16}

An «{-code-13{-code-16}unexpected{-code-1{-code-16}«{-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{-code-4{-code-16}

purposefully abstract/inexact operator+{-code-2{-code-16} diagram

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

            {-code-3{-code-16}
    
  2. String concatenation

    A frequent mishap are string concatenations with {-code-14{-code-16}gotten{-code-4{-code-16} operator:

                                    {-code-5{-code-16}
    

    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{-code-4{-code-16}

    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{-code-4{-code-16}

  3. Missing expression operators

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

                {-code-7{-code-16}
    

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

  4. Lists

    Same {-code-14{-code-16} syntax {-code-11{-code-16}s{-code-8{-code-16} like in array populations{-code-8{-code-16} where the parser also indicates an expected comma{-code-8{-code-16} {-code-14{-code-16} example:

                                           ⇓
     $var = array{-code-23}"{-code-13{-code-16}1"{-code-13{-code-16} =>{-code-13{-code-16} $val{-code-8{-code-16} $val2{-code-8{-code-16} $val3 $val4){-code-13{-code-16}
    

    Or functions parameter {-code-11{-code-16}s:

                                     ⇓
     function myfunc{-code-23}$param1{-code-8{-code-16} $param2 $param3{-code-8{-code-16} $param4)
    

    Equivalently do you see this with{-code-11{-code-16} or{-code-12{-code-16} statements{-code-8{-code-16} or when lacking a{-code-13{-code-16} semicolon in a{-code-14{-code-16} loop{-code-4{-code-16}

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

     class xyz {      ⇓
         var $value = $_GET["{-code-13{-code-16}input"{-code-13{-code-16}]{-code-13{-code-16}
    

    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{-code-4{-code-16}

  6. Variables after ident{-code-19}iers

    You can also never have a variable follow an ident{-code-19}ier directly:

                  ⇓
     $this->{-code-13{-code-16}myFunc$VAR{-code-23}){-code-13{-code-16}
    

    Btw{-code-8{-code-16} this is a common example where the intention was to use variable variables perhaps{-code-4{-code-16} In this case a variable property lookup with$this->{-code-13{-code-16}{"{-code-13{-code-16}myFunc$VAR"{-code-13{-code-16}{-code-16}{-code-23}){-code-13{-code-16} {-code-14{-code-16} example{-code-4{-code-16}

    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{-code-4{-code-16}

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

            ⇓
     {-code-14{-code-16}each $array as $key) {
    

    Solution: add the missing opening{-code-23} between statement and variable{-code-4{-code-16}

                           ⇓
     {-code-19} {-code-23}$var = pdo_query{-code-23}$sql) {
          $result = …
    

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

  8. Else does not expect conditions

         ⇓
    else {-code-23}$var >{-code-13{-code-16}= 0)
    

    Solution: Remove the conditions fromelse or use {-code-4{-code-16}

  9. Need brackets {-code-14{-code-16} closure

         ⇓
    function{-code-23}) use $var {{-code-16}
    

    Solution: Add brackets around$var{-code-4{-code-16}

  10. Invisible whitespace

    As mentioned in the reference answer on «{-code-13{-code-16}Invisible stray Unicode»{-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:

    <{-code-13{-code-16}?php
                              в‡ђ
    $var = new PDO{-code-23}{-code-4{-code-16}{-code-4{-code-16}{-code-4{-code-16}){-code-13{-code-16}
    

    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{-code-4{-code-16}

See also

  • Search: unexpected {-code-1{-code-16}


600

votes

Answer

Solution:

Unexpected T_CONSTANT_ENCAPSED_STRING
Unexpected T_ENCAPSED_AND_WHITESPACE

The unwieldy namesT_CONSTANT_ENCAPSED_STRING andT_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.

  1. Incorrect variable interpolation

    And it comes up most frequently for incorrect PHP variable interpolation:

                              ⇓     ⇓
    echo "Here comes a $wrong['array'] access";
    

    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:

    echo "This is only $valid[here] ...";
    

    Nested arrays or deeper object references however require the complex curly string expression syntax:

    echo "Use {$array['as_usual']} with curly syntax.";
    

    If unsure, this is commonly safer to use. It’s often even considered more readable. And better IDEs actually use distinct syntax colorization for that.

  2. Missing concatenation

    If a string follows an expression, but lacks a concatenation or other operator, then you’ll see PHP complain about the string literal:

                           ⇓
    print "Hello " . WORLD  " !";
    

    While it’s obvious to you and me, PHP just can’t guess that the string was meant to be appended there.

  3. Confusing string quote enclosures

    The same syntax error occurs when confounding string delimiters. A string started by a single' or double" quote also ends with the same.

                    ⇓
    print "<a href="' . $link . '">click here</a>";
          вЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџвЊћвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЋЅвЊџ
    

    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:

    print "<a href="{$link}">click here</a>";
    

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

  4. Missing opening quote

    Equivalently are forgotten opening a recipe for parser errors:

                   ⇓
     make_url(login', 'open');
    

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

  5. Array lists

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

    array(               ⇓
         "key" => "value"
         "next" => "....",
    );
    

    Note that the last line may always contain an extra comma, but overlooking one in between is unforgivable. Which is hard to discover without syntax highlighting.

  6. Function parameter lists

    The same thing for function calls:

                             ⇓
    myfunc(123, "text", "and"  "more")
    
  7. Runaway strings

    A common variation are quite simply forgotten string terminators:

                                    ⇓
    mysql_evil("SELECT * FROM stuffs);
    print "'ok'";
          ⇑
    

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

  8. HEREDOC indentation

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

    print <<< HTML
        <link..>
        HTML;
       ⇑
    

    Solution: upgrade PHP or find a better hoster.

See also

  • Interpolation (double quoted string) of Associative Arrays in PHP
  • PHP — syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
  • Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP
  • Unexpected T_CONSTANT_ENCAPSED_STRING error in SQL Query


416

votes

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.

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

                   ⇓                  ⇓
     {-code-11} {-code-5}<{-code-29}a href={-code-5}http://example.com{-code-5}>{-code-29}click here<{-code-29}/a>{-code-29}{-code-5}{-code-29}
    

    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:

    {-code-14} = {-code-6}<{-code-29}div>{-code-29}some text with {-code-25}php {-code-11} {-code-6}some php entry{-code-6} ?>{-code-29}<{-code-29}/div>{-code-29}{-code-6}
    

    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

    See also What is the difference between single-quoted and double-quoted strings in PHP?.

  2. Unclosed strings

    If you miss a closing then a syntax error typically materializes later. An unterminated string will often consume a bit of code until the next intended string value:

                                                           ⇓
    {-code-11} {-code-5}Some text{-code-5}, {-code-32}a_variable, {-code-5}and some runaway string {-code-29}
    success({-code-5}finished{-code-5}){-code-29}
             в‡Ї
    

    It{-code-6}s not just literals which the parser may protest then. Another frequent variation is an for unquoted literal HTML.

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

    {-code-14} = ’Something something..’ + {-code-20} ain{-code-6}t quotes”{-code-29}
    

    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.

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

           {-code-21}
    

    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.

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

          ⇓
    {-code-23} {-code-27}={-code-5}1.0{-code-5}?>{-code-29}
    


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-11-28

Link To Source

Link To Answer
People are also looking for solutions of the problem: gd library extension not available with this php installation.

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

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

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 symbol expecting register
  • Syntax error unexpected string at end of statement
  • Syntax error unexpected parseop zero
  • Syntax error unexpected main expecting
  • Syntax error unexpected integer number