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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.