Home  >  Article  >  Backend Development  >  php foreach pointer

php foreach pointer

WBOY
WBOYOriginal
2016-08-18 09:16:241396browse

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

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

}
//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>

}
//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>

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