~n[EO]n~ Posted November 29, 2007 Share Posted November 29, 2007 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 Quote Link to comment Share on other sites More sharing options...
Orio Posted November 29, 2007 Share Posted November 29, 2007 <?php $var = ""; for ($i = 1; $i <= 10; $i++) { if($i % 2 == 0) $var .= "Even Numbers : ". $i. "<br>"; else $var .="Odd Numbers : ". $i. "<br>"; } echo $var; ?> Orio. Quote Link to comment Share on other sites More sharing options...
~n[EO]n~ Posted November 29, 2007 Author Share Posted November 29, 2007 Lovely.... one question Can it be done without if..else ? Quote Link to comment Share on other sites More sharing options...
Orio Posted November 29, 2007 Share Posted November 29, 2007 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. Quote Link to comment Share on other sites More sharing options...
~n[EO]n~ Posted November 29, 2007 Author Share Posted November 29, 2007 Thanks a lot... this also shows the same result as above. And, yes this had to be done without if.... Quote Link to comment Share on other sites More sharing options...
Orio Posted November 29, 2007 Share Posted November 29, 2007 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.