alex
alex

Reputation: 490607

Is there a way to get "true"/"false" string values from a Boolean in PHP?

When I cast to Boolean (using (bool)), is there a built in way to get PHP to actually return the constants true or false. At the moment I'm getting 1 or blank, which evaluate to true and false respectively.

I want the value returned for clearer semantics. However, if I can't get it, I'll just settle with 1 and blank.

Upvotes: 6

Views: 6547

Answers (3)

kevin
kevin

Reputation: 1228

In case you're too lazy to do a comparison and echo a string or if you just want to keep it short you can use :

var_export($boolean, true); // the second parameter is to return and not output

PHP: var_export

Upvotes: 11

Dolph
Dolph

Reputation: 50710

If you're looking for the strings "true" and "false," a ternary conditional would be perfect:

<?=(($boolean) ? "true" : "false")?>

Upvotes: 0

cletus
cletus

Reputation: 625387

PHP displays boolean values as 1 (true) or empty string (false) when outputted.

If you want to check if it's true or false use == (if implicit conversion is OK) or === (if it's not). For example:

echo $val ? 'true' : 'false'; // implicit conversion
echo $val === true ? 'true' : 'false'; // no conversion

I don't know of any way to make PHP output boolean values natively as true or false.

Upvotes: 7

Related Questions