Reputation: 39
I'd like to add even numbers to an array and then echo it out, here's my code but it just shows array() when I print...what am i doing wrong?
<?php
$x =88;
$numbers = array();
while ($x % 2 == 0 && $x <= 99) {
$numbers[] = "$x";
$x++;
}
print_r($numbers);
?>
Upvotes: 0
Views: 63
Reputation: 27092
You should move the "evenness" test from the while
loop, and move it to a conditional within the while
loop:
<?php
$x = 88;
$numbers = array();
while ($x <= 99) {
if ($x % 2 == 0) {
$numbers[] = $x;
}
$x++;
}
print_r($numbers);
?>
As you have currently written the while
loop, it ends if the number is not even. You should also remove the quotes from $x
when you add to the $numbers
array.
Upvotes: 3