dpgjci27392 2013-06-04 10:16
浏览 121
已采纳

两个具有相同值的数组键

Just wondering how I can easily have two array keys with the same associative value. My current code is:

$arraytest = array(
        'test1', 'test2' => 1,
        'test3', 'test4' => 2,
)

I want the array to work so the following code returns:

$arraytest['test1'] returns 1
$arraytest['test2'] returns 1

etc

thanks for your help, m

  • 写回答

4条回答 默认 最新

  • dousong1926 2013-06-04 10:23
    关注

    you can associate the reference of one variable to two array keys to simulate this situation :

    e.g.

    $a = 2;
    
    $arraytest = array (
      'test1' => &$a,
      'test2' => &$a
    );
    

    This way, as 'test1' and 'test2' point to $a in memory you will always have the value of the "real" $a using 'test1' and 'test2' of the array. However keep in mind using references in arrays should be avoided since this can lead to unexpected program behaviors:

    from php.net documentation

    "Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value."

    More details here => What References Do (php.net)

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

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示