dongsibao8977 2013-10-31 16:59
浏览 32
已采纳

迭代和修改数组最佳方法

The following is the best way to iterate through and modify array in PHP5.*+

(source: http://zend-php.appspot.com/questions_list -- question #3)

$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
   $val += 1;
}

What is it about this method of iterating and modifying that makes it better than others?

Can someone please explain how come this actually works?

This iterates just fine, why include as $key => &$val if we are not using the keys?, also why do we need to include the & in &$val:

foreach($array as $val){
   echo $val;
}

I appreciate the explanation, Thanks in advance!

  • 写回答

2条回答 默认 最新

  • douyueqing1530 2013-10-31 17:08
    关注

    Since they intend to modify the value, getting it as a reference is clever.

    $array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
    foreach($array as $key => &$val) {
       $val += 1;
    }
    

    Will add 1 to all values.

    If you did:

    foreach($array as $key => $val) {
       $val += 1;
    }
    

    Nothing would happen.

    I strongly disagree that it is the best way though. I much prefer to see:

    foreach($array as $key => $val) {
       $array[$key] += 1;
    }
    

    because it's much more straightforward. I'll gladly believe it doesn't perform as well, but I also don't care (unless there is a reason to start optimizing).

    It's also worth mentioning that using references can lead to strange situations, such as: PHP reference causes data corruption

    PS. I didn't downvote. I'm getting really annoyed by people downvoting and not leaving a comment.

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

报告相同问题?

悬赏问题

  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统