PHP中的数组指针

Dustin Jia

我对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);
}

我真的不确定为什么会这样,有人可以帮助我吗?

齐雷尔

您将需要检查的结果current()是否不同于布尔值false(意味着光标没有找到该元素),而不仅仅是分配其值。当值为时0,您会得到while(0),这会中断循环。

$ages = [];
for($i = 0; $i < 10; $i++) {
  $ages[] = $i;
}
while($age = current($ages) !== false) {
  echo $age . ", ";
  next($ages);
}

https://3v4l.org/61WoL

但是,如果数组中的任何元素具有boolean的值,则此操作将失败false因此,完全不建议像这样遍历数组,而应该使用适当的工具(通过foreach循环)。这实际上并不会移动光标,但是您可以通过调用next()每次迭代来“使其”移动光标

$ages = [];
for($i = 0; $i < 10; $i++) {
  $ages[] = $i;
}
foreach ($ages as $age) {
    echo current($ages).", ";
    next($ages);
}

如果您只是想打印这些值,最好的方法是直接从foreach循环中打印或使用implode()

foreach ($ages as $age) {
    echo $age.", ";
}

要么

echo impolode(",", $ages);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章