Table of Contents
回复内容:
Home Backend Development PHP Tutorial foreach 传引用的时候有bug?

foreach 传引用的时候有bug?

Jun 06, 2016 pm 08:31 PM
foreach php Quote

$a = array(1,2,3);
var_dump($a);
foreach($a as &$b){}
var_dump($a);
foreach($a as $b){
var_dump($b);
}

下面是5.2到7.0的结果

array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
array(3) { [0]=> int(1) [1]=> int(2) [2]=> &int(3) }
int(1) int(2) int(2)

早期版本的输出请看http://3v4l.org/PXsWr

请问这是不是php的一个bug?

回复内容:

$a = array(1,2,3);
var_dump($a);
foreach($a as &$b){}
var_dump($a);
foreach($a as $b){
var_dump($b);
}

下面是5.2到7.0的结果

array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
array(3) { [0]=> int(1) [1]=> int(2) [2]=> &int(3) }
int(1) int(2) int(2)

早期版本的输出请看http://3v4l.org/PXsWr

请问这是不是php的一个bug?

提问之前 难道不应该先搜索一下的嘛....参考 foreach 指针

产生这个现象的原因是因为,两次foreach都用了$b,而foreach的过程是先进行赋值,所以在第二次循环的第一步,会把数组的第一项复制给指向最后一项的指针,因此导致了数组的最后一项改变了

$b在第二个foreach的时候,还是相当于&$a[2],所以惨剧发生了 -- $a[2]被修改了

这就是偶不喜欢使用foreach,而喜欢使用array_walk的原因:

<code>$a = array(1,2,3);
var_dump($a);
array_walk($a, function(&amp;$b){
   // do something
});
var_dump($a);
array_walk($a, function($b){
    var_dump($b);    // =&gt; int(1) int(2) int(3)
});
</code>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

CakePHP Date and Time

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

CakePHP Project Configuration

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

CakePHP File upload

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

CakePHP Routing

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

Discuss CakePHP

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP Quick Guide

See all articles