Tim Tim - 7 months ago 9
SQL Question

PHP Check if var is 0 or 1 and then print accordingly

Im getting an integer from my database that is either 0 or 1. With this information i want to change a string to say Esea. This is my code which isn't working:

<?php
$esea = '';

if (!empty($final_data['esea'])) {
$esea = 'Esea'
}

?>


Then this is where i print it:

<p><?php echo $esea ?></p>

Answer
$myvalue= '';

if (!empty($final_data['esea'])) {
    $myvalue= 'Foo'
} else {
    $myvalue= 'Bar'
}

echo $myvalue;

If the output is Foo then $final_data['esea'] was one of:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)

See the empty() documentation.

If the output is Bar then $final_data['esea'] was none of the above values.

Also see the comments here and here.

Also note that the above code can be rewritten to:

$myvalue= '';

if (empty($final_data['esea'])) {
    $myvalue= 'Bar'
} else {
    $myvalue= 'Foo'
}

echo $myvalue;

Which is functionally exactly the same. The only difference is emtpy(...) v.s. !empty(...) (and ofcourse the logic in the if/else swapped).

Comments