Detailed explanation of PHP foreach principle

不言
Release: 2023-03-24 18:32:02
Original
1675 people have browsed it

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
Copy after login
  • 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
Copy after login


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
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template