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);
}
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);
}
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);
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.",";
}