Home > Backend Development > PHP Tutorial > php foreach pointer

php foreach pointer

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-08-18 09:16:24
Original
1479 people have browsed it

$arr = array('a', 'b', 'c');
$i = 0;
foreach($arr as $key => $value) {

<code>if($i == 0) {
    //第一次就执行了写操作
    $arr[$key] = $value . $value;
}
$i++;</code>
Copy after login
Copy after login

}
//The pointer of $arr has been moved once, pointing to the second element b.
var_dump(current($arr));//b

Why does the pointer go to the second element at the beginning

Reply content:

$arr = array('a', 'b', 'c');
$i = 0;
foreach($arr as $key => $value) {

<code>if($i == 0) {
    //第一次就执行了写操作
    $arr[$key] = $value . $value;
}
$i++;</code>
Copy after login
Copy after login

}
//The pointer of $arr has been moved once, pointing to the second element b.
var_dump(current($arr));//b

Why does the pointer go to the second element at the beginning

<code>$arr = array('a', 'b', 'c');
$i = 0;
foreach($arr as $key => $value) {
    if($i == 0) {
        $arr[$key] = $value . $value;
    }
    $i++;
}

</code>
Copy after login

The pseudocode is the same

<code>$arr = array('a', 'b', 'c');
$i = 0;
$arrCopy = $arr; //复制出一个待循环数组的副本,接下来都是操作这个副本
$key = currentKey($arrCopy); //将获取到的值分配给$k;
$val = currentVal($arrCopy); //将获取到的值分配给$v;

//移动副本数组的指针,这边执行顺序比写时复制高,所以先移动
next($arrCopy);
$arr = $arrCopy;//将副本赋值回给$arr((主要是将指针同步移动))

{ //大括号的内容
    if($i == 0) {
        $arr[$key] = $value . $value;
    }
    $i++;
}


//然后第二次循环
$key = currentKey($arrCopy); 
$val = currentVal($arrCopy);
//移动副本数组的指针,这边执行顺序比写时复制高,所以先移动
next($arrCopy);
$arr = $arrCopy;//将副本赋值回给$arr((主要是将指针同步移动))

{ //大括号的内容
    if($i == 0) {
        $arr[$key] = $value . $value;
    }
    $i++;
}
//然后第三次循环
$key = currentKey($arrCopy); 
$val = currentVal($arrCopy);
//移动副本数组的指针,这边执行顺序比写时复制高,所以先移动
next($arrCopy);
$arr = $arrCopy;//将副本赋值回给$arr((主要是将指针同步移动))

{ //大括号的内容
    if($i == 0) {
        $arr[$key] = $value . $value;
    }
    $i++;
}</code>
Copy after login
Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template