dongxun5349 2014-05-08 01:25
浏览 69

PHP字符串嵌入式数组格式:“$ {arr [0]}”vs“{$ arr [0]}”

In PHP, you can embed an array directly in a (double-quoted) string, but it looks like there are two ways to do it; for example:

$arr[0]="foobar";
echo "${arr[0]}";
echo "{$arr[0]}";

They both seem to work, but what is the difference? Is either better?

(It’s frustratingly difficult to look this up due to Google’s lack of special-character support, but I have seen both formats in use.)

  • 写回答

3条回答 默认 最新

  • dqcd84732 2014-05-08 01:32
    关注

    Both work because both are valid. From the manual:

    Complex (curly) syntax

    This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

    Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.

    // Won't work, outputs: This is { fantastic}
    echo "This is { $great}";
    
    // Works, outputs: This is fantastic
    echo "This is {$great}";
    echo "This is ${great}";
    
    // Works
    echo "This square is {$square->width}00 centimeters broad."; 
    
    
    // Works, quoted keys only work using the curly brace syntax
    echo "This works: {$arr['key']}";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改