dongpao5658 2016-04-13 16:35
浏览 14
已采纳

嵌入变量值以形成新变量

I have a variable $var that can only be set to, let's say, a or b. I have two global arrays, e.g. $aNames and $bNames. Finally there's also a variable $number. To bring everything together, I'd like to combine the values to get an element from the array.

Example:

$var = 'a';
$number = 2;
$el = "$$var"."Names[".$number."]";

$el == $aNames[2] // true

But I'm not sure how to write that first $el line without it being interpreted as a string.

  • 写回答

1条回答 默认 最新

  • drkrsx3135168 2016-04-13 16:53
    关注

    This would do:

    $el = ${$var.'Names'}[$number];
    

    Example:

    <?php
    $aNames[2] = 10;
    $var = 'a';
    $number = 2;
    $el = ${$var.'Names'}[$number];
    echo $el; //10
    

    and now

    $el == $aNames[2]
    

    will evaluate to true

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置