Jump to content

How to give certain numbers color in PHP


user123454321

Recommended Posts

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
Link to comment
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
Link to comment
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.

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.