drnmslpz42661 2014-07-03 17:26
浏览 27
已采纳

数组上的奇怪打印

I'm testing the performances/hitches for References over copies of an array. I have the following code:

function ScoreWords($Value){
    $WordList = array(
        "Amazing" => 1,
        "Value" => 300,
        "Elements" => 30,
        "Another" => 0

    );

    if (array_key_exists($Value,$WordList)){
        return $WordList[$Value];
    }

}

$array = ["Value","Another",1,2,3,4];
echo implode(',', $array), "<br>";

foreach ($array as &$value) {
    ScoreWords($value);
}
echo implode(',', $array), "<br>";

foreach ($array as $value) {
    ScoreWords($value);
}    
echo implode(',', $array), "<br>";

But it seems, the code pasted above works semi-fine. Output is:

Value,Another,1,2,3,4

Value,Another,1,2,3,4

Value,Another,1,2,3,3

I found this by mistake as imploding was not actually necessary, but this sparks the question. Why is there a duplicated value for the final print rather than the correct value of 4? regardless of what the content of the array is. It seems to duplicate the second from last element as the last element?

  • 写回答

2条回答 默认 最新

  • dongshuo1856 2014-07-03 17:36
    关注

    What is happening is that after your 1st foreach, $value is a reference to the last element in the array. As that loop progressed it was a reference to each element, until finally stopping at the last one.

    So, when the 2nd foreach runs, $value is still a reference. As that loop runs, it updates $value, which in turn, updates the last element in the array.

    When it gets to the last element, it was set to 3 from the previous loop iteration. So, that's why it's set to 3 at the end.

    To fix this, unset($value); after your first foreach.

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比