Jump to content

How to give certain numbers color in PHP


user123454321

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

?>
Link to comment
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>";
}

 

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.

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

Archived

This topic is now archived and is closed to further replies.

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