Reputation: 5
I want to store for loop results as an array. The code repeats the results. Kindly correct me.
I did it on While loop it works perfectly.
$numbers=array();
$i=23;
while ($i <= 42){
if($i % 2 == 0){
$numbers[] = $i;
}
$i++;
}
echo '<pre>';
print_r($numbers);
echo ' </pre>';
For loop code:
$numbers=array();
for ($i==23; $i<=42; $i++){
if (!($i % 2)){
$numbers[]=$i;
echo '<pre>';
print_r($numbers);
echo '</pre>';
}
}
Upvotes: 0
Views: 90
Reputation: 149
change $i == 23 to $i = 23 and move echo to outside for loop.
$numbers=array();
for ($i=23; $i<=42; $i++){
if (!($i % 2)){
$numbers[]=$i;
}
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
You will get same result with while loop.
Array
(
[0] => 24
[1] => 26
[2] => 28
[3] => 30
[4] => 32
[5] => 34
[6] => 36
[7] => 38
[8] => 40
[9] => 42
)
Upvotes: 2