phparrayssyntax-errorparse-errorphp-parse-error

Why the parse error is being thrown upon using one array notation inside double-quoted string and and not upon using the other?


Consider below code :

<?php
   $arr = array('fruit' => 'apple', 'veggie' => 'carrot');

   define('fruit', 'veggie');

   print "Hello {$arr['fruit']}"; //This works

   print "Hello $arr['fruit']"; //This doesn't work
 ?>

I'm not able to understand why the second one is not working and giving me the parse error as follows :

**Parse error:** syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

Also if I write above program as below that is if I add die; after the first executing line and then put the non-working line still I get the same error.

 <?php
   $arr = array('fruit' => 'apple', 'veggie' => 'carrot');

   define('fruit', 'veggie');

   print "Hello {$arr['fruit']}";
   die;
   print "Hello $arr['fruit']";
 ?>

I didn't get this at all. It should have printed first line as I'm dying the code after it the line following die should not be considered while compiling but it's considering and prohibiting the first line from execution.

Why so?


Solution

  • The parse error is because of the way variables are being parsed inside a double-quoted string. You should read about that here.

    In the second example PHP interpretes $arr to be a string on which the brackets perform a substring kind of action. In that scenario the single quotes should not be there, causing a parse error.

    Which leads us to your second question: A parse error occurs while PHP tries to parse your PHP file. Since PHP does not yet know what comes after the die-statement (there may for example be a function there that you will call from another part of the script), it must parse every line. So a parse error does not care about execution logic yet.