我正在阅读PHP手册(特别是each()功能)并遇到以下警告:
Caution
Because assigning an array to another variable resets the original array’s pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.
一个例子:
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>
好的.这说得通.但我决定做一个简单的测试:
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
foreach ($fruit as $key => $name) {
printf("[%s] => [%s]\n", $key, $name);
}
$fruit2 = $fruit;
echo current($fruit);
?>
结果是预期的:指针已被重置.我的问题是指针是否仅在数组结束后重置?
例如:
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
foreach ($fruit as $key => $name) {
printf("[%s] => [%s]\n", $key, $name);
}
reset($fruit);
next($fruit)."\n";
$fruit2 = $fruit;
echo current($fruit);
?>
指针保留在第二个数组元素中(‘b’=>’banana’).
这种行为是语言的特征吗?
谢谢你,对不起英语不好意思.
解决方法:
This behavior is characteristic of language?
PHP数组中“指针”的含义与“指针”的一般含义不同(在C/C++或其他语言中,程序员可以直接访问内存).
PHP中没有指针. array数据类型将光标内部保留在其包含的值列表中.它被称为数组的内部指针,它由函数reset(),next(),prev(),end(),each()以及其他函数修改.它可以用于迭代数组,如下所示:
$array = array(1, 2, 3);
while (list($key, $val) = each($array)) {
echo($key.' => '.$val."\n");
}
没有可靠的方法来使用next()或prev()迭代数组,因为当没有更多元素要迭代时它们返回FALSE但是当值FALSE作为元素存储在数组中时它们也返回FALSE.
如果您只需要从数组的开头(或结尾)分析几个项目,它们可能很有用. F.E.假设我们有一个由函数返回的整数数组,我们需要得到第一个不为零的值.
但使用foreach()可以更轻松地实现这一目标:
$array = array(0, 0, 0, 2, 0, 1, 0, 3);
foreach ($array as $val) {
if ($val != 0) {
break;
}
}
echo($val); // prints "2"
或array_shift():
$array = array(0, 0, 0, 2, 0, 1, 0, 3);
do {
$val = array_shift($array);
if ($val != 0) {
break;
}
} while(count($array));
echo($val); // prints "2"
The result is expected: the pointer has been reset. My question is if the pointer is reset only after the end of the array?
foreach()的文档是错误的.也许它在PHP 3和PHP 4上是正确的,但我认为自从PHP 5中引入iterators以来,foreach()的行为发生了变化(更好).
它说:
When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.
一个简单的测试与此陈述相矛盾:
$array = array(1, 3, 5, 7, 9);
foreach ($array as $val1) {
foreach ($array as $val2) {
echo('$val1='.$val1.'; $val2='.$val2.'; ');
}
echo("\n");
}
它没有问题.如果foreach()使用内部数组指针,它应该不起作用.它可能会创建指针的副本.
您还可以尝试在foreach()中使用current(),next(),prev()或reset(),您将获得令人惊讶且有时不一致的结果.
最好使用foreach()迭代数组,不要以任何方式依赖内部指针.
但是,当您需要获取数组的第一个和最后一个元素而不必担心键时,函数reset()和end()非常方便.
标签:php,arrays,pointers
来源: https://codeday.me/bug/20190612/1222614.html