Jump to content
user123454321

How to give certain numbers color in PHP

Recommended Posts

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>";  
    } 

?>

Share this post


Link to post
Share on other sites

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>";
}

 

  • Like 1

Share this post


Link to post
Share on other sites

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 by ginerjm
  • Like 1

Share this post


Link to post
Share on other sites

PS - since the <font> tag is so-out-of-date, I suggest doing something other than that.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.