douyun1860 2017-11-26 04:29
浏览 45
已采纳

为什么我在访问字符串类型键下的数组值时出现解析错误? [重复]

This question already has an answer here:

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.

</div>
  • 写回答

1条回答 默认 最新

  • douwen8118 2017-11-26 04:34
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,