Alexandre Khoury
Alexandre Khoury

Reputation: 4022

Variable set to false

I wrote this REALLY simple code:

$foo=false;
echo $foo;//It outputs nothing

Why? Shouldn't it output false? What can I do to make that work?

Upvotes: 0

Views: 6050

Answers (3)

zeddex
zeddex

Reputation: 1300

If you want to see a "true" or "false" string when you echo for tests etc you could always use a simple function like this:

// Boolean to string function
function booleanToString($bool){
    if (is_bool($bool) === true) {
        if($bool == true){ 
            return "true";  
        } else { 
            return "false";
        } 
    } else { 
        return NULL;
    }
}

Then to use it:

// Setup some boolean variables 
$Var_Bool_01 = true;
$Var_Bool_02 = false;

// Echo the results using the function
echo "Boolean 01 = " . booleanToString($Var_Bool_01) . "<br />"; // true
echo "Boolean 02 = " . booleanToString($Var_Bool_02) . "<br />"; // false

Upvotes: 1

Matt
Matt

Reputation: 7040

false evaluates to an empty string when printing to the page.

Use

echo $foo ? "true" : "false";

Upvotes: 5

Brad
Brad

Reputation: 163436

The string "false" is not equal to false. When you convert false to a string, you get an empty string.

What you have is implicitly doing this: echo (string) $foo;

Upvotes: 3

Related Questions