0

I have tried following code :

<?php
  $juices = array("apple", "orange", "koolaid1" => "purple");

  // For below line of code I get tis error : Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
  echo "He drank some $juices['koolaid1'] juice.".PHP_EOL;

  // For below line of code too I get tis error : Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)
  echo "He drank some $juices["koolaid1"] juice.".PHP_EOL;

  //Below line of code works fine. Prints He drank some purple juice. 
  echo "He drank some $juices[koolaid1] juice.".PHP_EOL;
?>

My question is as the type of key I'm accessing is string then I should have to put it inside single or double quotes to get access to the value it holds. I'm doing the same thing here but getting a parse error. Why this is happening?

And on the other hand it's really very surprising to see that when I don't make use of single or double quotes around the key of string type it's working fine.

I got totally confused here due to this strange behavior of PHP. Please someone provide me useful help.

B. Desai
  • 16,414
  • 5
  • 26
  • 47

1 Answers1

1

When your array variable is already in double quotes " at that time you don't have to add any quotes for accessing index. You just have to directly write index name without any quotation. But If you don't have any quotes around array at that time you have to add quotation for accessing string index.

echo "He drank some $juices[koolaid] juice.".PHP_EOL; //No need any quotation

echo $juices['koolaid']; //Need quotation here

B. Desai
  • 16,414
  • 5
  • 26
  • 47