PHP: Determine Text Colour based on value - php

I've stored values in an array and I want to apply conditional formatting to the output when I access them.
I want the text of the values, less than or equal to 10, displayed in red or, greater than 10, displayed in green.
For example, below, I would like the resultant value of 5 to be displayed in red.
I'm a newbie to this but would assume I would need the help of CSS to achieve this.
Any advice would be appreciated.
<?php
$total_sql=array();
$total_sql[]=5;
$total_sql[]=10;
$total_sql[]=15;
$total_sql[]=20;
print($total_sql[0]);
?>

<?php
$total_sql=array();
$total_sql[]=5;
$total_sql[]=10;
$total_sql[]=15;
$total_sql[]=20;
print($total_sql[0]);
?>
foreach($total_sql as $item)
{
if($item >10)
{
echo '<p class="green">'.$item.'</p>';
} else {
echo '<p class="red">'.$item.'</p>';
}
.red{color:red;}
.green{color:green}

One liner:
echo '<div style="color: '.(($score == '5') ? 'red' : 'black').';">'.$score.'</div>';
Comparison operator could be:
$score == 'x'
> 'y'
>= 'z'
etc...
I've used an inline style here, but you can use class= too.

Related

Display Specific Image Based On SQL Query Result

I have a page that displays products based on a previous user query. The search results contain sets of metadata, most importantly a "product rating" on a 1-10 scale.
Here's the code that pulls the product rating metadata
<?php echo get_post_meta( get_the_ID(), 'product_rating', true ); ?>
This pulls the 'rating' metadata from our dB and simply displays the rating as a numeral (1, 1.5, 2, 2.5 ect).
I'm looking to take the value of the 'product_rating' and set an image to display for each value. A rating of 1 will display one image, while a rating of 2 display a different image ect ect.
The current code I have in place substitutes an image for the value, but the image is displaying multiple times (up to 10 times for a single value). My code is below, using a rating value of "4" as an example.
<?php $rating = get_post_meta( get_the_ID(), 'product_rating', true ); ?>
<?php For($i=4; $i <= $rating; $i++){
echo "<img src='http://www.domain.com/lpimage/lock50.png' />";
}
?>
Is my code close to where I need to be, or am I completely off base for the function I want?
Assuming your rating variable is correctly defined I think you can handle the conditional display of various images as follows:
<?php if ($rating == 1) echo '<img src="urlofimage1.jpg"></img>';
elseif ($rating == 2) echo '<img src="urlofimage2.jpg"></img>';
elseif ($rating == 3) echo '<img src="urlofimage3.jpg"></img>';
elseif ($rating == 4) echo '<img src="urlofimage4.jpg"></img>';
?>
You use the double equal sign when comparing a value, you only use the single equal sign (=) when setting a variable's value.
Use >= and <= for ranges, ie. 1.3 or 2.7

Different css styling for last element of a php array Pt.2

Ok here is my new issue, and a complete description of what I am trying to accomplish. I used the suggestions you gave me and it worked fine, but when I changed the ORDER by information to a different field and the if statement, it went crazy.
Here is what I need, I have two columns on a page, when the array is processed I need it to display results filling each column left to right top to bottom. There is a division line between each item
<div class="centerBoxContentsFeatured centeredContent back vLine " style="width:50%;">
and one under each item
<div class="product-col" >.
If the item is the 3rd, 5th, 7th and so on… it will be on the left and does not need the “vLine “ div before it and if it is the last item(s) it does not need the “product-col” div under it as the last 2 items do not have to have the bottom divider, but if it is only two items on the whole page the bottom divider can stay. What am I doing wrong?
<?php
$count_temp = count ($productid);
for ($i = 0; $i < $count_temp; ++$i) {
$artist = get_the_title();
if (($productartist[$i] == $artist ) && $categoryID[$i] ==1 ) {
?>
//Content//
<?php if (!($i === 0) && !($i % 2) &&
($productid[$i] == 1) &&
( $i === (count ($productid) - 1))) {
echo'<div class="product-col-none" >';
}
else { echo '<div class="product-col" >';}
?>
//Content//
<? if !( $i === (count ($productid) - 1))
{
echo '<div class="centerBoxContentsFeatured centeredContent back vLine " '.
'style="width:50%;">';
}
else {
echo '<div class="centerBoxContentsFeatured centeredContent back " '.
'style="width:50%;">';}
?>
You should write here about your css file code, you are making things complicated and unclear with your html embedded php code.
If you just want a different style for your odd numbered (3,5,7..) items and a different style for your last item then I'll recommend to use css pseudo classes
You can use css pseudo class last-child for your last item.
li:last-child
{
// Your specific style for last item goes here
}
You can also use css pseudo class nth-child(odd) for alternating odd numbered items
li:nth-child(odd)
{
// Your specific style for odd items goes here
}
I hope this is what you are looking for, Why to give a server side load when you can set things done at client end.

CSS – vertical order of elements [duplicate]

This question already has answers here:
HTML & CSS: Vertical Flow Layout (columnar style), how to implement?
(3 answers)
Closed 9 years ago.
As always, I have a "simple" question at first sight.
I have a div on my webpage containing a set of buttons (links, actually, but they serve as buttons). Simply put:
<div class="container">
text
text
text
text
</div>
Now what I need to do is to line them up in vertical order. What I mean is: normally if they appear as inline-block or inline element, they will line up horizontally one after another and when the line ends, the following link appears on the next one. The same goes for float: left.
But I need them to be in horizontal order – in other words, instead of rows, there will be columns with set height. When the column reaches the end, the following button should appear in the next column.
Is there a way to make that possible through CSS?
The only other way I can imagine is that I set a function in php or something like that but I'm not really good or knowledgeable about it. But I do have the option of putting it there so if you have this kind of solution, I'll be grateful too.
Thanks a lot.
Haven't yet tired, but hopes it helps.
$link_array = array();
$link_array[] = array('Google', 'http://google.com/');
$link_array[] = array('Yahoo', 'http://yahoo.com/');
$link_array[] = array('Bing', 'http://bing.com/');
$link_per_column = 10;
foreach ($link_array as $position => $this_link)
{
if ($position % $link_per_column === 0 && ($position === 0))
{
echo '<div class="column">';
echo "<a href='{$this_link[1]}'>{$this_link[0]}</a>";
}
elseif ($position % $link_per_column === 0 && ($position !== count($link_array)))
{
echo '</div><div class="column">';
echo "<a href='{$this_link[1]}'>{$this_link[0]}</a>";
}
elseif (($position === count($link_array)))
{
echo "<a href='{$this_link[1]}'>{$this_link[0]}</a>";
echo '</div>';
}
else
{
echo "<a href='{$this_link[1]}'>{$this_link[0]}</a>";
}
}

Numbers & css classes

How can I add a css class to a randomly generated number.
example:
if the number is under 2000 add a css class named red to the div <div class="red">500</div>
if the number is over 2000 add a css class named blue to the div <div class="blue">2500</div>
There are many ways this could be done, but here's one simple one. If $rNum holds your randomly-generated number we can test whether it is less than or equal to 2000. If it is, we'll print "red", and if it's not we'll print "blue".
<p class="<?php print ( $rNum <= 2000 ) ? "red" : "blue" ; ?>">Hello World</p>
If you're new to PHP you may find the syntax of the ternary operator to be somewhat confusion. It's basically a simplified inline if-else statement. You can see more examples and read a short description online at php.net.
you can first generate the rand number, store it into a variable and then use if..else to add the class to div element, like below:
<?php $rand = rand($min,$max); ?>
<div class="<?php if ( $rand <= 2000 ) echo "red"; else echo "blue" ; ?>"><?php echo $rand; ?></div>
Alternatively, add an id element to this div tag, and then use Javascript to add the class.
Do you want to do this?
<div class="<?php echo ($number<2000)?'red':'blue'; ?>">
<?php echo $number ?>
</div>

Multi column dynamic PHP list

So what I'm trying to do is select all the distinct months from my database and then print them in a list. That, I can accomplish. The problem lies in the fact that I need my list to be two column. The way that I achieve this with CSS is by using 2 different div's "left" and "right" which are floated next to each other. This poses a problem with PHP because it needs to echo a div close and a new div open after it echoes the sixth month. Then it needs to start again from where it left off and finish. I can't just list all of the months in the HTML, either because I don't want it to list a month if I don't have any records in the DB for that month, yet. Any ideas? I hope I was clear enough!
Thanks!
-williamg
Something like this should work (the basic idea being to just keep a count of the months an increment it as you loop through them):
<div class="left">
<?php
$x = 1;
foreach($months as $month) {
# switch to the right div on the 7th month
if ($x == 7) {
echo '</div><div class="right">';
}
echo "<div class=\"row\">{$month}</div>";
# increment x for each row
$x++;
}
</div>
<?php
$numberOfMonths = count($months);
$halfwayPoint = ceil($numberOfMonths / 2);
echo "<div class=\"left\">";
for($i=0; $i<$halfwayPoint; $i++){
echo $months[$i] . "<br />";
}
echo "</div><div class=\"right\">";
for($i=$halfwayPoint; $i<$numberOfMonths; $i++){
echo $months[$i] . "<br />";
}
echo "</div>";
?>
Rant: on
When displaying tabular data, use table instead of floating div. It will make sense when viewing the page with css disabled. If you use floated div, then you data will displayed all way down. Not all table usage is bad. People often hate table so much, so using floated div. Table only bad when used for page layout.
Rant: off
When I need to have certain content displayed with some open, close, and in-between extra character, I will make use of implode. This is the example:
$data = array('column 1', 'column 2');
$output = '<div>'.implode('</div><div>', $data).'</div>';
//result: <div>column 1</div><div>column 2</div>
You can extends this to almost anything. Array and implode is the power that php have for many years. You will never needed any if to check if it last element, then insert the closing character, or check if it first element, then insert opening character, or print the additional character between elements.
Hope this help.
Update:
My bad for misread the main problems asked. Sorry for the rant ;)
Here is my code to make a data displayed in 2 column:
//for example, I use array. This should be a result from database
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
//should be 12 month, but this case there are only 9 of it
for ( $i = 0; $i <= 5; $i++)
{
//here I do a half loop, since there a fixed number of data and the item for first column
$output = '<div class="left">'.$data[$i].'</div>';
if ( isset($data[$i+6] )
{
$output = '<div class="right">'.$data[$i+6].'</div>';
}
echo $output."\n";
}
//the result should be
//<div class="left">1</div><div class="right">7</div>
//<div class="left">2</div><div class="right">8</div>
//<div class="left">3</div><div class="right">9</div>
//<div class="left">4</div>
//<div class="left">5</div>
//<div class="left">6</div>
Other solution is using CSS to format the output, so you just put the div top to down, then the css make the parent container only fit the 6 item vertically, and put the rest to the right of existing content. I don't know much about it, since it usually provided by fellow css designer or my client.
Example assumes you have an array of objects.
<div style="width:150px; float:left;">
<ul>
<?php
$c = count($categories);
$s = ($c / 3); // change 3 to the number of columns you want to have.
$i=1;
foreach($categories as $category)
{
echo '<li>' . $category->CategoryLabel . '</a></li>';
if($i != 0 && $i % $s == 0)
{
?>
</ul>
</div>
<div style="width:150px; float:left;">
<ul>
<?php
}
$i++;
}
?>
</ul>
</div>

Categories