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 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!