Home >Backend Development >PHP Tutorial >Detailed explanation of PHP foreach principle

Detailed explanation of PHP foreach principle

不言
不言Original
2018-04-24 09:54:401688browse

This article introduces a detailed explanation of the PHP foreach principle, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

PHP foreach principle detailed explanation

  • When foreach starts executing, the pointer inside the array will automatically point to the first unit. This means there is no need to call reset() before the foreach loop. How to understand this?

$arr = array(1,2,3);foreach($arr as $k=>$v){

}
var_dump(current($arr));foreach($arr as $key=>$value){    echo $value." ";
}
var_dump(current($arr));

结果:boolean false

     1 2 3

     boolean false
  • Deepen the understanding of foreach

$arr = array(&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3);foreach($arr as $k=>$v){    $v*=2;    echo $v."<br />";
}
var_dump($arr);foreach($arr as $key=>$value){    $arr[$key]=$value*2;
}
var_dump($arr);//传入&foreach($arr as &$v){    $v=$v*2;
}$v = 0


var_dump($arr)

Result

246array (size=3)  &#39;a&#39; => int 1
  &#39;b&#39; => int 2
  &#39;c&#39; => int 3array (size=3)  &#39;a&#39; => int 2
  &#39;b&#39; => int 4
  &#39;c&#39; => int 6array (size=3) (不加 $v = 0)  &#39;a&#39; => int 4
  &#39;b&#39; => int 8
  &#39;c&#39; => &int 12array (size=3) (加 $v = 0)  &#39;a&#39; => int 4
  &#39;b&#39; => int 8
  &#39;c&#39; => 0

Related recommendations:

php leaves the reference problem of the array after the foreach loop

In PHP foreach reference passing address

Exception handling after foreach usage & reference in php

The above is the detailed content of Detailed explanation of PHP foreach principle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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