Jump to content

[SOLVED] for loop separating Even and Odd numbers... help


~n[EO]n~

Recommended Posts

Hi all,

Problem

I need to separate Even and Odd number based on the user input... I tried through for loop but could not display both in same code. If I comment either one of $var it works perfectly, but I am having problem displaying both...

<?php
for ($i = 1; $i <= 10; $i++) 
{
$var = "Even Numbers : ". ++$i. "<br>";
$var .="Odd Numbers : ". $i++. "<br>";
echo $var;
}
?>

 

It looks simple but where am i getting wrong ? Any help

In this very specific case, this would do the job

 

<?php

$var = "";


for ($i = 1; $i <= 10-1; $i++) 
{
$var .= "Odd Numbers : ". $i++ . "<br>";
$var .= "Even Numbers : ". $i . "<br>";
}

echo $var;

?>

 

But if you want to make a general version to print the numbers from a certain $start number until $end number, this will look totally different. Why don't you want to have an if clause?

 

Orio.

This is how I would do the general $start to $end case:

 

<?php

$start = 1;
$end = 10;

$odd = range($start + (1 - $start%2), $end - (1 - $end%2), 2);
$even = range($start + ($start%2), $end - ($end%2), 2);

foreach($odd as $num)
$odd_2[$num] = "Odd Numbers : ".$num."<br>";
foreach($even as $num)
$even_2[$num] = "Even Numbers : ".$num."<br>";

$numbers = $odd_2+$even_2;
ksort($numbers);

$var = implode("<br>", $numbers);
echo $var;

?>

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.