bech64
bech64

Reputation: 129

if, else if echo statement

If the value is 1 the cell bg is green with the # 1 in the cell If the value is 0 the cell bg is yellow with a 0 in it.

I would like to display "Yes" instead of "1" and "No" instead of "0"

     if($row['play']  == 1){
        echo "<td bgcolor='green'>" . $row['play'] . "</td>";
        }
     else if ($row['play']  == 0){
        echo "<td bgcolor='yellow'>" . $row['play'] . "</td>";
        }                    

The values come from a checkbox (1) and a hidden field (0) The MySQL field is BOOL.

Is there an easier/better way to achieve this?

Upvotes: 4

Views: 2764

Answers (6)

Ravi
Ravi

Reputation: 463

Try This

if($row['play']  == 1)
{
    echo "<td bgcolor='green'>Yes</td>";
}
 else if ($row['play']  == 0)
{
    echo "<td bgcolor='yellow'>No</td>";
}

Upvotes: 0

sybear
sybear

Reputation: 7784

$words = array(
 0 => "No",
 1 => "Yes"
) ;

if($row['play']  == 1){
  echo "<td bgcolor='green'>" . $words[(int)$row['play']] . "</td>";
} else if ($row['play']  == 0){
  echo "<td bgcolor='yellow'>" . $words[(int)$row['play']] . "</td>";
} 

Or even better:

$map = array(
  0 => array("word"=>"No", "color"=>"yellow"),
  0 => array("word"=>"Yes", "color"=>"green"),
) ;

$current = (int) $row['play'] ;
echo "<td bgcolor='{$map[$current]['color']}'>{$map[$current]['word']}</td>";

Upvotes: 0

christopher
christopher

Reputation: 27346

You can cut down on an echo statement by doing:

if($row['play']  == 1){
   $color = 'green';
   $text = 'yes';
}
else
{
   $color = 'red';
   $text = 'no'; 
}
// Assign the color and text values based on the input.

echo "<td bgcolor=$color>$data</td>";

Upvotes: 0

Mark
Mark

Reputation: 11

something like this will do it -

echo "<td bgcolor='" . $row['play'] == 1 ? "green" : "yellow" . "'> . $row['play'] == 1 ? "No" : "Yes" . "</td>";

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

You can cast it to an int, and then make a condition if it's above zero:

if((int)$row['play'] > 0) {
    echo "<td bgcolor='green'>Yes</td>";
}
else {
    echo "<td bgcolor='yellow'>No</td>";
}

This way, play could be 1, 2, 3, 4, 5, ..etc.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You can do this:

 if($row['play']  == 1){
    echo "<td bgcolor='green'>Yes</td>";
    }
 else if ($row['play']  == 0){
    echo "<td bgcolor='yellow'>No</td>";
    }    

but I'd say that switch/case thing is more comfortable:

switch( $row['play'] ) {
   case 1:
       echo "<td bgcolor='green'>Yes</td>";
       break;

   default:
       echo "<td bgcolor='yellow'>No</td>";
       break;
}

Upvotes: 6

Related Questions