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

Detailed explanation of PHP foreach principle

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

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('a'=>1,'b'=>2,'c'=>3);foreach($arr as $k=>$v){    $v*=2;    echo $v."
"; } 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!

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