0

My database has multiple boolean values. After I saved the database, the booleans got converted into tinyint(1). I think this is because it just needs to save 1 or 0.

However, I now have a problem comparing the value in PHP. I saved the tinyint into an array without any code-wise conversion. The array has multiple entries that are text and date and multiple entries with booleans, for example:

array[0] is '09:45:00'
array[1] is '10:45:00'
array[2] is 1
array[3] is 0
array[4] is 0
array[5] is 1
array[6] is 'active'

Now if I loop through the array I want to check if the value is a time, a text, or true/false.

Checking if the entry is true will always return true, because no entry is empty. Checking if the entry is 1 or 0 works for the boolean, but when I check if 'active' == 0 it is returning true. Why is this the case and how can I get a false if I compare a string with a tinyint?

Comparing with === does not work in any case.

Skalibran
  • 459
  • 1
  • 5
  • 19
  • 2
    `1 == true` and `0 == false`, using `===` is direct check (so it must match type etc.), using `==` will work for you – Can O' Spam Jul 05 '18 at 07:55
  • Unfortunately it also returns true if I check 'active' == 0 – Skalibran Jul 05 '18 at 07:58
  • You're doing this the wrong way around. The date types are part of the database design and not something you should infer from the query results. All columns might contain a null regardless of type so this will always break down in that case – apokryfos Jul 05 '18 at 08:00
  • @apokryfos So instead of saving 1 or 0, I should save 1 and allow NULL? I'll try that, thanks! – Skalibran Jul 05 '18 at 08:04
  • That's definitely not what I said. I said that if you have a NULL you can't know if that field was a date, number of string normally so you should just know what datatypes your fields are instead of trying to infer them after a query – apokryfos Jul 05 '18 at 08:04

1 Answers1

1

I think u can do this with some nested if-else statements. But I'm pretty sure there is a better-looking solution too. :)

$a=array('09:45:00','10:45:00',1,0,0,1,'active',3.12);

foreach ($a as $value) {
    $type= gettype($value);
    if ($type == "string") {
        if(strtotime ($value)){
            echo "$value is 'Time' \n";
        }
        else{
            echo "$value is 'String' \n";
        }
    } elseif ($type == "integer") {
        if($value == 0 || $value == 1){
            echo "$value is 'Boolean' \n";
        }
        else{
            echo "$value is 'Integer' \n";
        }
    } else{
        echo "$value is ($type)!";
    }
}
Wick96
  • 66
  • 7
  • Checking if the if the value that should be compared is_numeric does work pretty well as a workaround. Still, I'm wondering why 0 == 'string' is true... – Skalibran Jul 05 '18 at 08:27
  • U can find an answer to your question here: https://stackoverflow.com/questions/6843030/why-does-php-consider-0-to-be-equal-to-a-string – Wick96 Jul 05 '18 at 08:33