dongzhiyi2006 2013-05-05 18:43
浏览 11
已采纳

PHP变量名包含索引

$arr[0]=123;
$a="arr[0]";
echo $$a;

gives me error

Notice: Undefined variable: arr[0]

on the last line.

What should I do to make it work?


EDIT:

Above is the simplification of what I want to do. If someone wants to know why I want to do this, then here's the explanation:

This is something like what I want to do:

if(condition){
    $a=$arr1[0][0];
    $b=$arr1[0][1];
    $c=$arr1[0][2];
}
else{
    $a=$arr2[0];
    $b=$arr2[1];
    $c=$arr2[2];
}

I can compact it like this:

if(condition)
    $arr=$arr1[0];
else
    $arr=$arr2;
$a=$arr[0];
$a=$arr[1];
$a=$arr[2];

But I wanted to try doing this using variable variable:

if(condition)
    $arr="$arr1[0]";
else
    $arr="$arr2";
$a={$$arr}[0];
$b={$$arr}[1];
$c={$$arr}[2];

Sure, we don't need variable variables as we can still code without them. I want to know, for learning PHP, why the code won't work.

  • 写回答

4条回答 默认 最新

  • doushao1087 2013-05-05 19:34
    关注

    Now that you said what you’re actually trying to accomplish: Your code doesn’t work because if you look at $arr1[0][0], only arr is the variable name; the [0] are special accessors for certain types like strings or arrays.

    With variable variables you can only specify the name but not any accessor or other operation:

    A variable variable takes the value of a variable and treats that as the name of a variable.

    Your solution with the additional variable holding the array to access later on would be the best solution to your problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教