Hidden Danger of References inside a Foreach Construct

来源:互联网 发布:slice 数组 编辑:程序博客网 时间:2024/04/29 04:50

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

That's a fact we've known for years. But I don't use it very often for it never works for me. My code is simplified as follows.

<?php//This is the file content$file = '<?php exit;?>::11365393847/healthcom/memcp.do{"idnum":"450521199309333489","password":"123459"}{"action":"login"}::11365393858/healthcom/register.do{"info":"thisis a test"}[]::11365393869/healthcom/memcp.do{"idnum":"450521199309333489","password":"123459"}{"action":"login"}';//We read it and explode it into an array$logs = explode("\r\n", $file);unset($logs[0]);//Handle each lineforeach($logs as &$log){if(empty($log)){continue;}$log = explode("\t", $log);$log[1] = date($log[1]);}//Output the content directly. (Maybe you'd rather output the HTML in another file with a template engine.)foreach($logs as $log){print_r($log);}?>

There seems no problems. Unfortunately I got the output like this:

Array(    [0] => ::1    [1] => 1365393847    [2] => /healthcom/memcp.do    [3] => {"idnum":"450521199309333489","password":"123459"}    [4] => {"action":"login"})Array(    [0] => ::1    [1] => 1365393858    [2] => /healthcom/register.do    [3] => {"info":"thisis a test"}    [4] => [])Array(    [0] => ::1    [1] => 1365393858    [2] => /healthcom/register.do    [3] => {"info":"thisis a test"}    [4] => [])

The last record was unexpectedly modified. I've been trying to find out what the problem it is. 


There's a warning in the PHP manual.

Reference of a $value and the last array element remain even after theforeach loop. It is recommended to destroy it byunset().


In the foreach construct, we've seen the $log is assigned a new value for each line. But the previous $log won't be affected because PHP seems to unset the reference on each loop ends and then start the next loop. But what on hell happened? Why the final log was modified in the second foreach construct?

I tried to output the $logs with print_r($logs); instead of a foreach. It wasn't modified.

It's noticed that reference $log wasn't destroyed in the last loop of the first statement. So when the second one starts, $log (references to $logs[3]) was assigned a new value, $logs[1].


In conclusion, although $log won't be affected in each loop, $log will be still there until you unset it. And as an easily overlooked assignment statement, the foreach construct can be a hidden danger. Just unset every reference when it becomes unnecessary.


<?phpforeach($logs as &$log){//Handle your $log}unset($log); //Don't miss me after each foreach construct with a reference. I'm in the PHP manual, but easily overlooked.?>

Ha, now it works as expected~

原创粉丝点击