Parse error syntax error unexpected else

I edit this code to display a mesaje when select is null and i get this error: Parse error: syntax error, unexpected 'else' (T_ELSE) in /nginx/user/reports.php on line 235 This is code: $stmt = $

I edit this code to display a mesaje when select is null and i get this error:

 Parse error: syntax error, unexpected 'else' (T_ELSE) in /nginx/user/reports.php on line 235

This is code:

 $stmt = $mysqli->prepare("SELECT date, impressions, balance, username FROM reports WHERE username = '$username' and date between '$firstDay' AND '$lastDay'");
    $stmt->execute();
    $stmt->store_result();
    $rows = $stmt->num_rows;
    mysqli_stmt_bind_result($stmt,$date,$impressions,$balance,$username);
       if ($rows > 0){
       while (mysqli_stmt_fetch($stmt)) {   
           $ecpm_t3 = $balance*1000;
       $ecpm3 = $ecpm_t3/$impressions;
    $rate = number_format((float)$ecpm3, 2, '.', '');
     echo"<tr>
            <td class="nn" style="text-align:center;" align=center>$date</td>
            <td class="nn" style="text-align:center;" align=center>$impressions</td>
            <td class="nn" style="text-align:center;" align=center>$$rate</td>
            <td class="nn" style="text-align:center;" align=center nowrap>$$balance</td>
        </tr>";
       } else {
        echo"<tr>
            <td colspan="4" class="nn" style="text-align:center;" align=center>Not rows</td>
        </tr>";
    }
        }

And line 235 is:

   } else {

How i can resolve this error ? What is bad ?

asked Jan 12, 2014 at 13:41

user3164987's user avatar

5

Working example (fixed and formatted):

$stmt = $mysqli->prepare("SELECT date, impressions, balance, username FROM reports WHERE username = '$username' and date between '$firstDay' AND '$lastDay'");
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
mysqli_stmt_bind_result($stmt, $date, $impressions, $balance, $username);
if ($rows > 0)
  {
    while (mysqli_stmt_fetch($stmt))
      {
        $ecpm_t3 = $balance * 1000;
        $ecpm3   = $ecpm_t3 / $impressions;
        $rate    = number_format((float)$ecpm3, 2, '.', '');
        echo "<tr>
                <td class="nn" style="text-align:center;" align=center>$date</td>
                <td class="nn" style="text-align:center;" align=center>$impressions</td>
                <td class="nn" style="text-align:center;" align=center>$$rate</td>
                <td class="nn" style="text-align:center;" align=center nowrap>$$balance</td>
              </tr>";
      }
   }
   else
     {
       echo "<tr>
               <td colspan="4" class="nn" style="text-align:center;" align=center>Not rows</td>
             </tr>";
     }

answered Jan 12, 2014 at 13:49

Ilia's user avatar

IliaIlia

12.9k11 gold badges52 silver badges85 bronze badges

Try this

<?php

$stmt = $mysqli->prepare("SELECT date, impressions, balance, username FROM reports WHERE username = '$username' and date between '$firstDay' AND '$lastDay'");
    $stmt->execute();
    $stmt->store_result();
    $rows = $stmt->num_rows;
    mysqli_stmt_bind_result($stmt,$date,$impressions,$balance,$username);
       if ($rows > 0){
       while (mysqli_stmt_fetch($stmt)) {   
           $ecpm_t3 = $balance*1000;
       $ecpm3 = $ecpm_t3/$impressions;
    $rate = number_format((float)$ecpm3, 2, '.', '');
     echo"<tr>
            <td class="nn" style="text-align:center;" align=center>$date</td>
            <td class="nn" style="text-align:center;" align=center>$impressions</td>
            <td class="nn" style="text-align:center;" align=center>$$rate</td>
            <td class="nn" style="text-align:center;" align=center nowrap>$$balance</td>
        </tr>";
       }} else {
        echo"<tr>
            <td colspan="4" class="nn" style="text-align:center;" align=center>Not rows</td>
        </tr>";
    }


?>

answered Jan 12, 2014 at 13:50

user1844933's user avatar

user1844933user1844933

3,3232 gold badges25 silver badges42 bronze badges

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


  1. Tom_as

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

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    Parse error: syntax error, unexpected T_ELSE, expecting T_WHILE in Y:hometest1.ruwwwindex.php on line 660

    Привожу код:

    1. $sel = isset( $_POST[‘sel’] ) ? $_POST[‘sel’] : isset( $_GET[‘sel’] ) ? $_GET[‘sel’] : «»;
    2.         if ( isset( $_COOKIE[‘dp_login’], $_COOKIE[‘dp_pass’] ) )
    3.             $strSQL = «SELECT id FROM «.USERS_TABLE.» WHERE login='».addslashes( $_COOKIE[‘dp_login’] ).«‘ AND password='».addslashes( $_COOKIE[‘dp_pass’] ).«‘ «;
    4.             $rs = $dbconn->execute( $strSQL );
    5.             if ( 0 < $rs->fields[0] )
    6.                 $user = auth_index_user( );
    7.             $user = auth_index_user( );
    8.                 if ( !isset( $_POST[‘remember_me’] ) )

    660 строка это последнее else между фигурными скобками. Не особо я понимаю чет в чем дело. если там должно быть while по тексту ошибки, то ошибка не исчезает.

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]


  2. WildZero

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

    С нами с:
    24 фев 2010
    Сообщения:
    242
    Симпатии:
    0
    Адрес:
    Пермь

    Скобка перед последним else должна быть перед while.


  3. tommyangelo

    с вложенностью разберись, у тебя получилось do … else


  4. Tom_as

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

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    я убрал сейчас из кода

    else
    {
    setcookie( «dp_login», «», time( ) — 7200 );
    setcookie( «dp_pass», «», time( ) — 7200 );
    }

    вот эту часть кода и все заработало….так я и не понял в смысле должна быть перед while

    ток потом правда еще одна ошибка появилась: Parse error: syntax error, unexpected ‘}’, expecting T_WHILE in Y:hometest1.ruwwwincludefunctions_index.php on line 85

    85я строчка это $id_lang_by_ip = $IpInfo->id_lang; после первого if

    1.     $file_name = isset( $_SERVER[‘PHP_SELF’] ) ? afterlastslash( $_SERVER[‘PHP_SELF’] ) : «index.php»;
    2.     $IpInfo = new ipinfo( $dbconn, $config );
    3.     if (!isset($_COOKIE[«language_cd»]) && GetSiteSettings(‘lang_ident_feature’)){
    4.         $id_lang_by_ip = $IpInfo->id_lang;
    5.         if ($id_lang_by_ip > 0 && $config[«default_lang»] != $id_lang_by_ip){
    6.             header(«location: index.php?language_code=».$id_lang_by_ip);
    7.     $elements = elementsforquicksearch( );
    8.     $smarty->assign( «elements», $elements );
    9.     banners( getrightmodulepath( __FILE__ ) );
    10.     $smarty->assign( «lang_link», getlangs( ) );

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]


  5. Roomlife

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

    С нами с:
    6 авг 2010
    Сообщения:
    34
    Симпатии:
    0

    там где у вас две скобки } (перед $elements = elementsforquicksearch( ); ) надо поставить третью, чтобы закрыть функцию


  6. Tom_as

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

    С нами с:
    10 авг 2010
    Сообщения:
    3
    Симпатии:
    0

    Блин точно, чет я даже и не заметил этого…спасибо огромное. эх…тяжело чужой код редактировать блин….


  7. WildZero

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

    С нами с:
    24 фев 2010
    Сообщения:
    242
    Симпатии:
    0
    Адрес:
    Пермь

    Дак установи себе какой нибудь notepad++, и не мучайся ты со скобками.


  8. T0n

    С нами с:
    13 окт 2015
    Сообщения:
    1
    Симпатии:
    0

    Господа, та же проблема с «PHP Parse error: syntax error, unexpected T_ELSE» родилась при переезде на другой VPS. Код не менялся, а функционал закончился ((, причем хостер ссылается именно на эту ошибку при попытках разобраться. Итак, речь идет о подбросе фотки и последующем ее редактировании. Суть первого файла заключается в следующем:

    1. <p><strong>Выбирите файл для загрузки (до 5 MБ , с расширением jpg или gif):</strong></p>
    2.         <FORM ENCTYPE=»multipart/form-data» ACTION=»zagruzka_obrabotka.php» METHOD=POST>
    3. <p><INPUT NAME=»myfile» TYPE=»file»  size=»40″ size=»5Mb» class=»inputField»><br><br>
    4. <INPUT class=»dobav» TYPE=»submit» name=»button» VALUE=»Загрузить»></p>
    5. {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}
    6. Обработка во втором файле выглядит так:
    7. // права на папку посмотреть:
    8. //echo substr(sprintf(‘%o’, fileperms(‘/etc/passwd’)), -4);
    9.      //echo $_SERVER[‘DOCUMENT_ROOT’].$dir;
    10.  if (!is_dir($_SERVER[‘DOCUMENT_ROOT’].‘/’.$dir)){
    11. //chmod($_SERVER[‘DOCUMENT_ROOT’].$dir, 0777);
    12.         $src=$dir.$_FILES[«myfile»][«name»];    
    13.     $dest=«foto/$a/ava.jpg» ;
    14.       function img_resize_real($src, $dest, $width, $height, $rgb=0xFFFFFF, $quality=83)
    15.          if ($size === false) return false;
    16.          // Определяем исходный формат по MIME-информации, предоставленной
    17.          // функцией getimagesize, и выбираем соответствующую формату
    18.          // imagecreatefrom-функцию.
    19.          $icfunc = «imagecreatefrom» . $format;
    20.          if ($set_w == 0 && $set_h == 0) { $set_w = $src_w; $set_h = $src_h; }
    21.          if ($set_w > 0 && $set_h == 0)  { $set_h = ceil($src_h*$set_w/$src_w); }
    22.          if ($set_h > 0 && $set_w == 0)  { $set_w = ceil($src_w*$set_h/$src_h); }
    23.          $prc_w = ceil($src_w*$set_h/$src_h);
    24.          $prc_h = ceil($src_h*$set_w/$src_w);
    25.              $out_w = $set_w; $out_h = $prc_h;
    26.              $out_w = $prc_w; $out_h = $set_h;
    27.              $xw = ceil($set_w*$src_h/$set_h);
    28.              $src_x = ceil(($src_w$xw)/2);
    29.              $xh = ceil($set_h*$src_w/$set_w);
    30.              $src_y = ceil(($src_h$xh)/2);
    31.          if ($out_w > $set_w || $out_h > $set_h)
    32.                  $h = ceil($out_h*$set_w/$out_w); $w = $set_w;
    33.                  $w = ceil($out_w*$set_h/$out_h); $h = $set_h;
    34.              $w = $out_w; $h = $out_h;
    35.          // Создаем новое изображение
    36.          // Копируем существующее изображение в новое с изменением размера:
    37.          $idest,  // Идентификатор нового изображения
    38.          $isrc,  // Идентификатор исходного изображения
    39.          0,0,      // Координаты (x,y) верхнего левого угла
    40.          $src_x,$src_y, // Координаты (x,y) верхнего левого угла копируемого
    41.          // блока существующего изображения
    42.          $out_w,    // Новая ширина копируемого блока
    43.          $out_h,    // Новая высота копируемого блока
    44.          $size[0], // Ширина исходного копируемого блока
    45.          $size[1]  // Высота исходного копируемого блока
    46.          if ($aaa<>true) {echo «<strong>Произошла ошибка! Попробуйте еще раз</strong>»;} 
    47.          return array(‘width’ => $out_w, ‘height’=> $out_h);
    48.     if (img_resize_real(«$src«,«foto/$a/ava.jpg»,240, 320))
    49.     {echo ‘<strong>Фото успешно загружено</strong>’;
    50.     printf(‘<p>[url=»kabinet.php?a=%s»]Мой кабинет[/url]</p><br>’,$danie88[«id»]);
    51.         else                          ———————- МЕСТО УКАЗАНИЯ НА ОШИБКУ СИНТАКСИСА
    52.         {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}          ——— ПОСЛЕДНИЙ ВЫВОД
    53. else {echo «<strong>По такому запросу страница не сконфигурирована</strong>»;}

    Итак, два вопроса:
    1.Почему один и тот же код на разных серверах работает по-разному?
    2.Для обеспечения работоспособности продолжать пинать хостера или действительно, что-то подправить в скрипте?

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]

I am trying to loop through custom post types and the code makes the page completely white but when I view source I can see my error:

Parse error: syntax error, unexpected 'else' (T_ELSE)

Here is my code, I am not sure why this is breaking as it was copy and pasted from a tutorial, I have tried it in numerous different template files and I get the same error so the error is secluded to this hunk of code:

 <?
$args = array( 'post_type' => 'members_features', 'posts_per_page' => 6 );
$the_query = new WP_Query( $args );
?>
<? if ( $the_query->have_posts() ) : ?>
<? while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><? the_title(); ?></h2>
    <div class="entry-content">
        <? the_content(); ?> 
    </div>
        <? wp_reset_postdata(); ?>
<? else:  ?>
    <p><? _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<? endif; ?>

The query recieves 1 row of data when I dump it and the query works fine, just the PHP notice is breaking my site, can any one help?

fuxia's user avatar

fuxia

105k34 gold badges246 silver badges447 bronze badges

asked Nov 9, 2015 at 14:47

Ric's user avatar

2

You aren’t ending your while before doing your else:

$args = array( 'post_type' => 'members_features', 'posts_per_page' => 6 );
$the_query = new WP_Query( $args );
?>
<? if ( $the_query->have_posts() ) : ?>
<? while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><? the_title(); ?></h2>
    <div class="entry-content">
        <? the_content(); ?> 
    </div>
        <? wp_reset_postdata(); ?>
<?php /** no endwhile! **/
<? else:  ?>
    <p><? _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<? endif; ?>

It’s easier to see the issue without the HMTL:

$args = array( 'post_type' => 'members_features', 'posts_per_page' => 6 );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        the_title();
        the_content(); 
        wp_reset_postdata();
        else: 
            _e( 'Sorry, no posts matched your criteria.' );
    endif;

answered Nov 9, 2015 at 14:58

phatskat's user avatar

phatskatphatskat

2,9691 gold badge15 silver badges26 bronze badges

1

Your while loop is not Ended. Throw in an

<? endwhile; ?>

before the wp_reset_postdata.

answered Nov 9, 2015 at 14:58

HU is Sebastian's user avatar

HU is SebastianHU is Sebastian

2,4431 gold badge11 silver badges14 bronze badges

You are missing the endwhile loop statement

    <div class="entry-content">
        <? the_content(); ?>
    </div>
    <? endwhile; ?>

answered Nov 9, 2015 at 14:59

Scriptonomy's user avatar

ScriptonomyScriptonomy

5734 silver badges9 bronze badges

What are syntax errors?

PHP belongs to the C-style and imperative programming languages. It has rigid grammar rules, which it cannot recover from when encountering misplaced symbols or identifiers. It can’t guess your coding intentions.

Most important tips

There are a few basic precautions you can always take:

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

  • Use an IDE or editor for PHP with syntax highlighting. Which also help with parentheses/bracket balancing.

  • Read the language reference and examples in the manual. Twice, to become somewhat proficient.

How to interpret parser errors

A typical syntax error message reads:

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

Which lists the possible location of a syntax mistake. See the mentioned file name and line number.

A moniker such as T_STRING explains which symbol the parser/tokenizer couldn’t process finally. This isn’t necessarily the cause of the syntax mistake however.

It’s important to look into previous code lines as well. Often syntax errors are just mishaps that happened earlier. The error line number is just where the parser conclusively gave up to process it all.

Solving syntax errors

There are many approaches to narrow down and fix syntax hiccups.

  • Open the mentioned source file. Look at the mentioned code line.

    • For runaway strings and misplaced operators this is usually where you find the culprit.

    • Read the line left to right and imagine what each symbol does.

  • More regularly you need to look at preceding lines as well.

    • In particular, missing ; semicolons are missing at the previous line end / statement. (At least from the stylistic viewpoint. )

    • If { code blocks } are incorrectly closed or nested, you may need to investigate even further up the source code. Use proper code indentation to simplify that.

  • Look at the syntax colorization!

    • Strings and variables and constants should all have different colors.

    • Operators +-*/. should be be tinted distinct as well. Else they might be in the wrong context.

    • If you see string colorization extend too far or too short, then you have found an unescaped or missing closing " or ' string marker.

    • Having two same-colored punctuation characters next to each other can also mean trouble. Usually operators are lone if it’s not ++--, or parentheses following an operator. Two strings/identifiers directly following each other are incorrect in most contexts.

  • Whitespace is your friend. Follow any coding style.

  • Break up long lines temporarily.

    • You can freely add newlines between operators or constants and strings. The parser will then concretise the line number for parsing errors. Instead of looking at very lengthy code, you can isolate the missing or misplaced syntax symbol.

    • Split up complex if statements into distinct or nested if conditions.

    • Instead of lengthy math formulas or logic chains, use temporary variables to simplify the code. (More readable = fewer errors.)

    • Add newlines between:

      1. Code you can easily identify as correct,
      2. The parts you’re unsure about,
      3. And the lines which the parser complains about. 

      Partitioning up long code blocks really helps locating the origin of syntax errors.

  • Comment out offending code.

    • If you can’t isolate the problem source, start to comment out (and thus temporarily remove) blocks of code.

    • As soon as you got rid of the parsing error, you have found the problem source. Look more closely there.

    • Sometimes you want to temporarily remove complete function/method blocks. (In case of unmatched curly braces and wrongly indented code.)

    • When you can’t resolve the syntax issue, try to rewrite the commented out sections from scratch.

  • As a newcomer, avoid some of the confusing syntax constructs.

    • The ternary ? : condition operator can compact code and is useful indeed. But it doesn’t aid readability in all cases. Prefer plain if statements while unversed.

    • PHP’s alternative syntax (if:/elseif:/endif;) is common for templates, but arguably less easy to follow than normal { code } blocks.

  • The most prevalent newcomer mistakes are:

    • Missing semicolons ; for terminating statements / lines.

    • Mismatched string quotes for " or ' and unescaped quotes within.

    • Forgotten operators, in particular for string . concatenation.

    • Unbalanced ( parentheses ). Count them in the reported line. Are there an equal number of them?

  • Don’t forget that solving one syntax problem can uncover the next.

    • If you make one issue go away, but another crops up in some code below, you’re mostly on the right path.

    • If after editing a new syntax error crops up in the same line, then your attempted change was possibly a failure. (Not always though.)

  • Restore a backup of previously working code, if you can’t fix it.

    • Adopt a source code versioning system. You can always view a diff of the broken and last working version. Which might be enlightening as to what the syntax problem is. 
  • Invisible stray Unicode characters: In some cases you need to use a hexeditor or different editor/viewer on your source. Some problems cannot be found just from looking at your code.

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

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

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

    • Which is occasionally an issue for MacOS users (even on OS X for misconfigured editors).

    • It often only surfaces as an issue when single-line // or # comments are used. Multiline /*...*/ comments do seldomly 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 any more. 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.

  • Don’t use PHP’s reserved keywords as identifiers for functions / methods, classes or constants.

  • Trial-and-error is your last resort.

If all else fails, you can always google your error message. Syntax symbols aren’t as easy to search for ( 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

Enabling it within the broken script is too late, because PHP can’t even interpret/run the first line. A quick workaround is crafting a wrapper script, say test.php:

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", 1);
   include("./broken-script.php");

Then invoke the failing code by accessing this wrapper script.

It also helps to enable PHP’s error_log and look into your webserver’s error.log when a script crashes with HTTP 500 responses.


Unexpected [

These days, the unexpected [ array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array().

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ⇑

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

$result = get_whatever()["key"];
                      ⇑

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

See also:

  • PHP syntax for dereferencing function result → possible as of PHP 5.4
  • PHP syntax error, unexpected ‘[‘
  • Shorthand for arrays: is there a literal syntax like {} or []?
  • PHP 5.3.10 vs PHP 5.5.3 syntax error unexpected ‘[‘
  • PHP Difference between array() and []
  • PHP Array Syntax Parse Error Left Square Bracket «[«

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you’re really clingy with older + slower PHP versions.

Other causes for Unexpected [ syntax errors

If it’s not the PHP version mismatch, then it’s oftentimes a plain typo or newcomer syntax mistake:

  • protected $var["x"] = "Nope";
                  ⇑
    
  • Confusing [ with opening curly braces { or parentheses ( is a common oversight.

    foreach [$a as $b)
            ⇑
    

    Or even:

    function foobar[$a, $b, $c] {
                   ⇑
    
  • Or trying to dereference constants (before PHP 5.6) as arrays:

    $var = const[123];
           ⇑
    

    At least PHP interprets that const as a constant name.

    If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil — so it becomes a $varname.

Unexpected ] closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array ] bracket.

  • Again mismatches with ) parentheses or } curly braces are common:

    function foobar($a, $b, $c] {
                              ⇑
    
  • Or trying to end an array where there isn’t one:

    $var = 2];
    

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

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

    If so, use your IDE for bracket matching to find any premature ] array closure. At the very least use more spacing and newlines to narrow it down.


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

  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.

    echo "This is only $valid[here] ...";
    
    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 " escapes 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

                   ⇓
     make_url(login', 'open');
    

    Here the ', ' would become a string literal after a bareword, when obviously login 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

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

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


Unexpected (

Opening parentheses typically follow language constructs such as if/foreach/for/array/list or start an arithmetic expression. They’re syntactically incorrect after "strings", a previous (), a lone $, and in some typical declaration contexts.

  1. Function declaration parameters

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

    Parameters in a function declaration can only be literal values or constant expressions. Unlike for function invocations, where you can freely use whatever(1+something()*2) etc.

  2. Class property defaults

    Same thing for class member declarations, where only literal/constant values are allowed, not expressions:

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

    Again note that PHP 7 only allows var $xy = 1 + 2 +3; constant expressions there.

  3. JavaScript syntax in PHP

    Using JavaScript or jQuery syntax won’t work in PHP for obvious reasons:

    <?php      ⇓
        print $(document).text();
    

    When this happens, it usually indicates an unterminated preceding string; and literal <script> sections leaking into PHP code context.

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

    Both isset() and empty() are language built-ins, not functions. They need to access a variable directly. If you inadvertently add a pair of parentheses too much, then you’d create an expression however:

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

    The same applies to any language construct that requires implicit variable name access. These built-ins are part of the language grammar, therefore don’t permit decorative extra parentheses.

    User-level functions that require a variable reference -but get an expression result passed- lead to runtime errors instead.

Unexpected )

  1. Absent function parameter

    You cannot have stray commas last in a function call. PHP expects a value there and thusly complains about an early closing ) parenthesis.

                  ⇓
    callfunc(1, 2, );
    

    A trailing comma is only allowed in array() or list() constructs.

  2. Unfinished expressions

    If you forget something in an arithmetic expression, then the parser gives up. Because how should it possibly interpret that:

                   ⇓
    $var = 2 * (1 + );
    

    And if you forgot the closing ) even, then you’d get a complaint about the unexpected semicolon instead.

  3. Foreach as constant

                       ↓    ⇓
    foreach ($array as wrong) {
    

    PHP here sometimes tells you it expected a :: instead. Because a class::$variable could have satisfied the expected $variable expression..

Unexpected {

Curly braces { and } enclose code blocks. And syntax errors about them usually indicate some incorrec nesting.

  1. Unmatched subexpressions in an if

    Most commonly unbalanced ( and ) are the cause if the parser complains about the opening curly { appearing too early. A simple example:

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

    Count your parens or use an IDE which helps with that. Also don’t write code without any spaces. Readability counts.

  2. { and } in expression context

    You can’t use curly braces in expressions. If you confuse parentheses and curlys, it won’t comply to the language grammer:

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

    There are a few exceptions for identifier construction, such as local scope variable ${references}.

  3. Variable variables or curly var expressions

    This is pretty rare. But you might also get { and } parser complaints for complex variable expressions:

                          ⇓
    print "Hello {$world[2{]} !";
    

    Though there’s a higher likelihood for an unexpected } in such contexts.

Unexpected }

When getting an «unexpected }» error, you’ve mostly closed a code block too early.

  1. Last statement in a code block

    It can happen for any unterminated expression.

    And if the last line in a function/code block lacks a trailing ; semicolon:

    function whatever() {
        doStuff()
    }            ⇧
    

    Here the parser can’t tell if you perhaps still wanted to add + 25; to the function result or something else.

  2. Invalid block nesting / Forgotten {

    You’ll sometimes see this parser error when a code block was } closed too early, or you forgot an opening { even:

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

    In above snippet the if didn’t have an opening { curly brace. Thus the closing } one below became redundant. And therefore the next closing }, which was intended for the function, was not associatable to the original opening { curly brace.

    Such errors are even harder to find without proper code indentation. Use an IDE and bracket matching.

Unexpected {, expecting (

Language constructs which require a condition/declaration header and a code block will trigger this error.

  1. Parameter lists

                     ⇓
    function whatever {
    }
    
  2. Control statement conditions

      ⇓
    if {
    }
    

    Which doesn’t make sense, obviously. The same thing for the usual suspects, for/foreachwhile/do, etc.

    If you’ve got this particular error, you definitely should look up some manual examples.


Unexpected T_IF 
Unexpected T_ELSEIF 
Unexpected T_ELSE 
Unexpected T_ENDIF

Conditional control blocks ifelseif and else follow a simple structure. When you encounter a syntax error, it’s most likely just invalid block nesting → with missing { curly braces } — or one too many.

  1. Missing { or } due to incorrect indentation

    Mismatched code braces are common to less well-formatted code such as:

    if((!($opt["uniQartz5.8"]!=$this->check58)) or (empty($_POST['poree']))) {if
    ($true) {echo"halp";} elseif((!$z)or%b){excSmthng(False,5.8)}elseif (False){
    

    If your code looks like this, start afresh! Otherwise it’s unfixable to you or anyone else. There’s no point in showcasing this on the internet to inquire for help.

    You will only be able to fix it, if you can visually follow the nested structure and relation of if/else conditionals and their { code blocks }. Use your IDE to see if they’re all paired.

    if (true) {
         if (false) {
                  …
         }
         elseif ($whatever) {
             if ($something2) {
                 …
             } 
             else {
                 …
             }
         }
         else {
             …
         }
         if (false) {    //   a second `if` tree
             …
         }
         else {
             …
         }
    }
    elseif (false) {
        …
    }
    

    Any double } } will not just close a branch, but a previous condition structure. Therefore stick with one coding style; don’t mix and match in nested if/else trees.

    Apart from consistency here, it turns out helpful to avoid lengthy conditions too. Use temporary variables or functions to avoid unreadable if-expressions.

  2. IF cannot be used in expressions

    A surprisingly frequent newcomer mistake is trying to use an if statement in an expression, such as a print statement:

                       ⇓
    echo "<a href='" . if ($link == "example.org") { echo …
    

    Which is invalid of course.

    echo "<a href='" . ($link ? "http://yes" : "http://no") . "</a>";
    
    if ($link) { $href = "yes"; } else { $href = "no"; }
    echo "<a href='$href'>Link</a>";
    

    Defining functions or methods for such cases often makes sense too.

    Control blocks don’t return «results»

    Now this is less common, but a few coders even try to treat if as if it could return a result:

    $var = if ($x == $y) { "true" };
    

    Which is structurally identical to using if within a string concatenation / expression.

    • But control structures (if / foreach / while) don’t have a «result».
    • The literal string «true» would also just be a void statement. 

    You’ll have to use an assignment in the code block:

    if ($x == $y) { $var = "true"; }
    

    Alternatively, resort to a ?: ternary comparison.

    If in If

                        ⇓
    if ($x == true and (if $y != false)) { ... }
    

    Which is obviously redundant, because the and (or or) already allows chaining comparisons.

  3. Forgotton ; semicolons

    Once more: Each control block needs to be a statement. If the previous code piece isn’t terminated by a semicolon, then that’s a guaranteed syntax error:

                    ⇓
    $var = 1 + 2 + 3
    if (true) { … }
    

    Btw, the last line in a {…} code block needs a semicolon too.

  4. Semicolon too early

    Now it’s probably wrong to blame a particular coding style, as this pitfall is too easy to overlook:

                ⇓
    if ($x == 5);
    {
        $y = 7;
    }
    else           ←
    {
        $x = -1;    
    }
    

    Which happens more often than you might imagine.

    • When you terminate the if () expression with ; it will execute a void statement. The ; becomes a an empty {} of its own!
    • The {…} block thus is detached from the if, and would always run.
    • So the else no longer had a relation to an open if construct, which is why this would lead to an Unexpected T_ELSE syntax error. 

    Which also explains a likewise subtle variation of this syntax error:

    if ($x) { x_is_true(); }; else { something_else(); };
    

    Where the ; after the code block {…} terminates the whole if construct, severing the else branch syntactically.

  5. Not using code blocks

    It’s syntactically allowed to omit curly braces {} for code blocks in if/elseif/else branches. Which sadly is a syntax style very common to unversed coders. (Under the false assumption this was quicker to type or read).

    However that’s highly likely to trip up the syntax. Sooner or later additional statements will find their way into the if/else branches:

    if (true)
        $x = 5;
    elseif (false)
        $x = 6;
        $y = 7;     ←
    else
        $z = 0;
    

    But to actually use code blocks, you do have to write {} them as such!

    Even seasoned programmers avoid this braceless syntax, or at least understand it as an exceptional exception to the rule.

  6. Else / Elseif in wrong order

    if ($a) { … }
    else { … }
    elseif ($b) { … }
    ↑
    

    You can have as many elseifs as you want, but else has to go last. That’s just how it is.

  7. Class declarations

    As mentioned above, you can’t have control statements in a class declaration:

    class xyz {
        if (true) {
            function ($var) {}
        }
    

    You either forgot a function definition, or closed one } too early in such cases.

  8. Unexpected T_ELSEIF / T_ELSE

    This is more or less a variation of incorrect indentation — presumably often based on wrong coding intentions.
    You cannot mash other statements inbetween if and elseif/else structural tokens:

    if (true) {
    }
    echo "in between";    ←
    elseif (false) {
    }
    ?> text <?php      ←
    else {
    }
    

    Either can only occur in {…} code blocks, not in between control structure tokens.

    • This wouldn’t make sense anyway. It’s not like that there was some «undefined» state when PHP jumps between if and else branches.
    • You’ll have to make up your mind where print statements belong to / or if they need to be repeated in both branches. 

    Nor can you part an if/else between different control structures:

    foreach ($array as $i) {
        if ($i) { … }
    }
    else { … }
    

    There is no syntactic relation between the if and else. The foreach lexical scope ends at }, so there’s no point for the if structure to continue.

  9. T_ENDIF

    If an unexpected T_ENDIF is complained about, you’re using the alternative syntax style if: ⋯ elseif: ⋯ else: ⋯ endif;. Which you should really think twice about.

    • As indentation is harder to track in template files, the more when using the alternative syntax — it’s plausible your endif; does not match any if:.

    • Using } endif; is a doubled if-terminator. 

    While an «unexpected $end» is usually the price for a forgotten closing } curly brace.

  10. Assignment vs. comparison

    So, this is not a syntax error, but worth mentioning in this context:

           ⇓
    if ($x = true) { }
    else { do_false(); }
    

    That’s not a ==/=== comparison, but an = assignment. This is rather subtle, and will easily lead some users to helplessly edit whole condition blocks. Watch out for unintended assignments first — whenver you experience a logic fault / misbeheviour.


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

Control constructs such as ifforeachforwhilelistglobalreturndoprintecho may only be used as statements. They usually reside on a line by themselves.

  1. Semicolon; where you at?

    Pretty universally have you missed a semicolon in the previous line if the parser complains about a control statement:

                 ⇓
    $x = myfunc()
    if (true) {
    

    Solution: look into the previous line; add semicolon.

  2. Class declarations

    Another location where this occurs is in class declarations. In the class section you can only list property initializations and method sections. No code may reside there.

    class xyz {
        if (true) {}
        foreach ($var) {}
    

    Such syntax errors commonly materialize for incorrectly nested { and }. In particular when function code blocks got closed too early.

  3. Statements in expression context

    Most language constructs can only be used as statements. They aren’t meant to be placed inside other expressions:

                       ⇓
    $var = array(1, 2, foreach($else as $_), 5, 6);
    

    Likewise can’t you use an if in strings, math expressions or elsewhere:

                   ⇓
    print "Oh, " . if (true) { "you!" } . " won't work";
    // Use a ternary condition here instead, when versed enough.
    

    For embedding if-like conditions in an expression specifically, you often want to use a ?: ternary evaluation.

    The same applies to forwhileglobalecho and a lesser extend list.

              ⇓
    echo 123, echo 567, "huh?";
    

    Whereas print() is a language builtin that may be used in expression context. (But rarely makes sense.)

  4. Reserved keywords as identifiers

    You also can’t use do or if and other language constructs for user-defined functions or class names. (Perhaps in PHP7. But even then it wouldn’t be advisable.)


Unexpected T_LNUMBER

In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore.

$1   // Bad
$_1  // Good

So little code, so many errors …

Let’s start with the three you haven’t noticed, because they are the most important:

1) Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:

SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: «x’;DROP TABLE MyTable;—» Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

A perfectly valid SELECT

DROP TABLE MyTable;

A perfectly valid «delete the table» command


And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don’t you?

2) Never store passwords in clear text — it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]3)

And remember: if this is web based then GDPR applies and that means you need to handle passwords as sensitive data and store them in a safe and secure manner. Text is neither of those and the fines can be …. um … outstanding. In December 2018 a German company received a relatively low fine of €20,000 for just that.

3) Never hard-code connection strings: if your code ever gets to production, it will fail immediately, because you connection string refers to a local instance of SQL server, and that won’t be the case. Always store connection strings in a configuration file!

Now, the one you have noticed by can’t fix yourself.
Look at the error message, it tells you two critical pieces of information: The error message «unexpected ‘else'» and where it found it «on line 52».
So look at line 52 (most editors accept CTRL+G as a «go to line number» command):

else {

That matches what the error message says, so look upwards to find it’s matching if:

if(count($row)!==0)
{
$databasepassword = $row[0]['password'];
if($databasepassword === $password) {
  ?>
  <script>
  alert('Login Successful');
  </script>
  <?php
}
else {
  ?>
  <script>
  alert('Login Failed');
  </script>
  <?php
}
else {
  echo"All fields are required!";
}

There isn’t one — probably because you forgot the closing curly bracket for teh if it should be «attached» to.
Move the closing curly bracket and correct the indentation to match.

  1. Home

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

963 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-18

Write your answer


278

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.


115

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)


686

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.


632

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}


816

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


725

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

Link To Source

Link To Answer
People are also looking for solutions of the problem: trying to access array offset on value of type bool

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.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Brian O'Connor

Hi, I’m getting the following error message when I try to display any of the items in the catalogue,

my code looks like this

  <?php 
if (strtolower($item["category"]) == "books"); { ?>
      <tr>
        <th>Authors</th>
        <td><?php echo implode(", ",$item["authors"]); ?></td>
        </tr>
        <tr>
        <th>Publisher</th>
        <td><?php echo $item["publisher"]; ?></td>
        </tr>
        <tr>
        <th>ISBN</th>
        <td><?php echo $item["isbn"]; ?></td>
        </tr>


        <?php } else if (strtolower($item["category"]) == "movies") { ?>
        <tr>
        <th>Director</th>
        <td><?php echo ,$item["director"]; ?></td>
        </tr>
        <tr>
        <th>Writers</th>
        <td><?php echo implode(", ",$item["writers"]); ?></td>
        </tr>
        <tr>
        <th>Stars</th>
        <td><?php echo implode(", ",$item["stars"]); ?></td>
        </tr>

         <?php } else if (strtolower($item["category"]) == "music") { ?>
        <tr>
        <th>Artist</th>
        <td><?php echo ,$item["artist"]; ?></td>
        </tr>
        <?php }?>

I am not seeing the error in the else if statement — my code should the same as the code used in the video — what am I missing ?

many thanks
Brian

2 Answers

Nicholas Mejia March 7, 2016 8:53pm

You’ve got a semi colon in front of your first if argument. Also, get rid of those commas that come after your echo statements. Do that and everything should work perfectly B)

Brian O'Connor

Thank you very much for that, the semi colon was the biggest culprit. I’m finding the most common mistake in my code so far on this learning journey is usually always a spelling or a single misplacement of a comma, colon, semi colon etc.

thank you again
B

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Parse error syntax error unexpected catch
  • Parse error style sheets should not include html syntax что значит
  • Parse error style sheets should not include html syntax перевод
  • Parse error python
  • Parse error possibly incorrect indentation or mismatched brackets haskell

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии