1

When I run the code given below, it outputs nothing in the browser. What Am I doing wrong? Please help.

$ages = [0, 4, 8, 12, 16, 20];

while ($age = current($ages)) {
    echo $age . ",";
    next($ages);
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
k2r2n2
  • 19
  • 2
  • 3
    Hint: what does `current($ages)` return in the first iteration? – El_Vanja Mar 03 '21 at 09:04
  • Related Javascript page: [Why does the while loop stop when condition check variable becomes 0?](https://stackoverflow.com/q/39974993/2943403) – mickmackusa May 10 '23 at 23:11
  • A similar PHP fail on a zero value in a loop: [strpos of 0 breaking while loop](https://stackoverflow.com/q/28591826/2943403) – mickmackusa May 10 '23 at 23:21

2 Answers2

5

The first test made is while (0), because the first value is 0. So, the loop is never executed.

You can use a foreach() loop instead

$ages = [0, 4, 8, 12, 16, 20];
foreach ($ages as $age) {
    echo $age . ',';
}

Or just implode() for a better result (because it will not have a trailing ,).

echo implode(',', $ages);
Syscall
  • 19,327
  • 10
  • 37
  • 52
5

To fix your current problem, when you use current($ages) in the first iteration of the loop, this will return the first item in the list - which is 0. As the while loop only continues whilst the value is not false (which 0 also counts) the loop will not be run, so...

while(($age = current($ages)) !== false){
    echo $age.",";
    next($ages);
}

alternatively, use a foreach loop...

foreach ( $ages as $age)    {
    echo $age.",";
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55