Home >Backend Development >PHP Tutorial >Detailed explanation of PHP foreach principle
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
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('a'=>1,'b'=>2,'c'=>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) 'a' => int 1 'b' => int 2 'c' => int 3array (size=3) 'a' => int 2 'b' => int 4 'c' => int 6array (size=3) (不加 $v = 0) 'a' => int 4 'b' => int 8 'c' => &int 12array (size=3) (加 $v = 0) 'a' => int 4 'b' => int 8 'c' => 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!