1

I'm very confused. I have several "float" fields in a mysql database. They either have 0,1,3 or 5 as the value (default is set to be 0). If the value is 0, the field is "off" for my purposes. If it has 1, 3 or 5, it's "on". I was checking like this...

if ($row['field1'] == "0") {
    $field1 = "off";
} else {
    $field1 = "on";
}

But I noticed that the field in mysql WAS 0, yet it was returning "on".

So I removed the quotes, like this...

if ($row['field1'] == 0) {
    $field1 = "off";
} else {
    $field1 = "on";
}

And it correctly returned "off".

However, not all fields are behaving the same, even thought they are all floats.

After removing quotes, I removed the quotes in all the other float field checks, but now they are returning the opposite of what they should be.

In other words, sometimes the quotes seem to be necessary, sometimes not, when checking if it has a 0 in the field. But I know that shouldn't be the case.

So figured I'd start her by learning what the truly proper way is, with quotes around 0 or not?

1
  • use empty($row['field1']) , empty function check value of datatype. Commented Apr 18, 2017 at 2:59

2 Answers 2

1

If your data is truly numeric, then you can test whether it is zero as follows:

if($row['field']==0) $field1='off';
else $field1='on';

You can put it more simply using the conditional (ternary) operator as follows:

$field1 = $row['field1']==0 ? 'off' : 'on';

or even more simply using the falsy value of 0 as follows:

$field1 = $row['field1'] ? 'off' : 'on';

In any case, you test without quotes, as the value is numeric.

If you suspect that the data is coming through as a string, you should try:

$field1 = floatval($row['field1'])==0 ? 'off' : 'on';

Note:

  • '0' as a string will test as truthy, while 0 as a number will test as falsy. This can account for a mis-match
  • floatval can be used to convert a string to a matching floating-point number. A non-valid string will be converted to 0.
Sign up to request clarification or add additional context in comments.

2 Comments

I might need to store decimals in this field too. So in addition to 1,3 and 5, it could be "0.125" for example. Is "float" the best option for these values?
@user3304303 float is fine. However, in that case you should use the PHP function floatval, so that it doesn’t end up truncating the value. I’ll fix my answer.
1

You can use empty to test for a falsey value, which will include 0, false and null

if (empty($row['field1'])) {
    $field1 = "off";
} else {
    $field1 = "on";
}

As far as "the truly proper way", that is a matter of opinion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.