PHP 中的数组指针

我对PHP中的数组指针有点困惑。下面的代码工作正常:


$ages = [1, 3, 5];

while($age = current($ages)) {

  echo $age . ", ";

  next($ages);

}

但是我不知道为什么下面的代码没有打印出任何东西:


$ages = [];

for($i = 0; $i < 10; $i++) {

  $ages[] = $i;

}

while($age = current($ages)) {

  echo $age . ", ";

  next($ages);

}

我也尝试使用for循环进行打印,但在下面的代码中只打印了for循环,while循环仍然没有打印。


$ages = [];

for($i = 0; $i < 10; $i++) {

  $ages[] = $i;

}

for($i = 0; $i < 10; $i++) {

  echo $ages[$i] . ", ";

}

while($age = current($ages)) {

  echo $age . ", ";

  next($ages);

}

我真的不知道为什么它表现得这样,任何人都可以帮我吗?


一只甜甜圈
浏览 98回答 3
3回答

LEATH

为什么它表现得像这样博士:由于新创建的数组的第一个元素 is 和 赋值运算符返回分配给变量的值,这会导致表达式计算为 ,因此 while-loop 的主体永远不会运行。0false运行 for 循环后,接收到的数组将为 。[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]首先,调用 将返回新创建的数组的第一个元素,即 ,然后赋值运算符将返回分配给变量的值,即 。然后,代码将是:current($ages)0=$age0while(0) {&nbsp; echo $age . ", ";&nbsp; next($ages);}0被评估为假,这就是为什么循环的主体永远不会运行的原因。因此,没有输出到屏幕。

白板的微信

您需要检查 的结果是否与布尔值不同(意味着游标未找到该元素),而不仅仅是分配其值。当值为 时,你会得到 ,这会破坏循环。current()false0while(0)$ages = [];for($i = 0; $i < 10; $i++) {&nbsp; $ages[] = $i;}while($age = current($ages) !== false) {&nbsp; echo $age . ", ";&nbsp; next($ages);}https://3v4l.org/61WoL但是,如果数组中的任何元素具有布尔值,这将失败。因此,根本不建议像这样循环访问数组,而应该使用正确的工具,使用循环。这实际上不会移动光标,但您可以通过调用每次迭代来“使其”移动光标。falseforeachnext()$ages = [];for($i = 0; $i < 10; $i++) {&nbsp; $ages[] = $i;}foreach ($ages as $age) {&nbsp; &nbsp; echo current($ages).", ";&nbsp; &nbsp; next($ages);}如果您只想打印值,最好的方法是直接从循环打印,或者使用 .foreachimplode()foreach ($ages as $age) {&nbsp; &nbsp; echo $age.", ";}或echo impolode(",", $ages);

天涯尽头无女友

首先,你的php代码的语法是错误的:将第 5 行替换为while($age == current($ages)) {你用的不是用来比较的,而是用来比较的。尝试这样做,然后看看。===此外,你可以用一种更简单的方式做到这一点:foreach($ages as $age) {&nbsp; echo "$age, ";}
打开App,查看更多内容
随时随地看视频慕课网APP