user123454321 Posted January 29, 2019 Share Posted January 29, 2019 I am trying to learn PHP basics, and I just cant figure out a way to insert color when certain conditions are met. In my code below, I want to print out red color on lets say, odd numbers from 20-49. Appreciate your help big time! <?php for ($i=20; $i<=49; $i++){ echo "$i<br>"; } ?> Quote Link to comment Share on other sites More sharing options...
gw1500se Posted January 29, 2019 Share Posted January 29, 2019 You can use the modulo operator (%). If you divide by 2 the remainder will be zero for even numbers and non-zero for odd numbers. For example: if ($i%2>0) { echo "<font style=\"color:red\">$i</font>"; } else { echo "<font style=\"color:blue\">$i</font>"; } 1 Quote Link to comment Share on other sites More sharing options...
ginerjm Posted January 29, 2019 Share Posted January 29, 2019 (edited) Since PHP doesn't actually "do" color, I would suggest that you use CSS. Setup a set of colors in your CSS area and then as you loop thru the numbers and create the HTML that will output those, assign a CSS classname. First the CSS <style> .color_1_10 {color:red;} .color_11_20 {color:blue;} .color_21_30 {color:green;} .color_more {color:black;} </style> Now the PHP for ($i=20; $i<=49; $i++) { switch ($i) { case <= 10: $clsname = 'class_1_10'; break; case <= 20: $clsname = 'class_11_20'; break; case <= 30: $clsname = 'class_21_30'; break; default: $clsname = 'class_more'; break; } echo "<span class='$clsname'>$i</span><br>"; } Note that I used a different range of numbers, but I think you get the idea. Edited January 29, 2019 by ginerjm 1 Quote Link to comment Share on other sites More sharing options...
ginerjm Posted January 29, 2019 Share Posted January 29, 2019 PS - since the <font> tag is so-out-of-date, I suggest doing something other than that. Quote Link to comment Share on other sites More sharing options...
gw1500se Posted January 29, 2019 Share Posted January 29, 2019 I was trying to keep it simple to start. Yes, using CSS is the modern way to do it but your solution does not address the whole question. It does not base the selected color on whether it is odd or even. Quote Link to comment Share on other sites More sharing options...
ginerjm Posted January 29, 2019 Share Posted January 29, 2019 PS - I goofed in my typing. The classnames that I assigned are mistyped. The span line should use class assignments that match those classes I defined in the CSS code part. As for my misunderstanding the criteria, change the switch code then. The scheme is still the same. 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.