Logical problems in PHP

I have a question about bools in php. I have a stored mysql proc that returns a boolean value. When this value is captured on the php side, it displays the value as 0 or 1. It all seems fine to me, and I read in the php manual that php will interpret 0 or 1 as false or true at compile time, it seems to me that it is not. I took another step and chose the return value (bool), but this still does not work.

Because of this, my if statements do not quit. Does anyone know what is going on? Thanks for the help.

+3
source share
4 answers

MySQL does not have proper data types BOOLor BOOLEAN. They are declared synonyms for TINYINT(1). Your procedure will return 0 or 1, which on a non-PHP basis will be converted to a string in the land of PHP, so in PHP you have lines '0'and '1'.

It is strange, however, that boolean casting does not convert them to the corresponding Boolean. You may have other errors in your code.

Are you trying to pass a direct result from a query? Because it is probably an array and:

var_dump((bool) array('0')); // true

Perhaps this is your problem. Check the result.

+4
source

It looks like a boolean is returned as a string.

Try something like this:

$your_bool = $field_value === "0" ? false : true;
+1
source

script . ( HTML "Boolean" , , , Firefox , ).

, , MySQL 0 1; TINYINT PHP, PHP false, TINYINT.

4 , (int) - , PHP true false MySQL TINYINT. MySQL PHP- , PHP.

echo "Boolean true=".true;
echo "Boolean false=".false;
echo "Boolean (int)true=".(int)true;
echo "Boolean (int)false=".(int)false;

PHP 5.3.1 MySQL 5.1.41:

Boolean true=1
Boolean false=
Boolean (int)true=1
Boolean (int)false=0

ABOUT! PHP literal literals can be lowercase or uppercase with the same result ... try it yourself.

+1
source

I use the useful "to_bool" function for something that I am not sure about type:

function to_bool($value, $default = false)
{
    if (is_bool($value)) {
        return $value;
    }
    if (!is_scalar($value)) {
        return $default;
    }
    $value = strtolower($value);
    if (strpos(";1;t;y;yes;on;enabled;true;", ";$value;") !== false) {
        return true;
    }
    if (strpos(";0;f;n;no;off;disabled;false;null;;", ";$value;") !== false) {
        return false;
    }
    return $default;
}

Then:

if (to_bool($row['result'])) { ... }
0
source

Source: https://habr.com/ru/post/1741951/


All Articles