Ioannis Papaioannou
Ioannis Papaioannou

Reputation: 177

PHP - print the result of a boolean expression

I expect the following code to print "false"

<?php
    $a = 4;
    $b = 45;
    echo $a==$b;
?>

but prints nothing.

Upvotes: 1

Views: 828

Answers (2)

Oran Fry
Oran Fry

Reputation: 31

false is rendered as an empty string('') in PHP, true as '1'.

These days json_decode() is an easy, reliable option to get 'true'/'false' if you're sure your variable or expression result is a boolean:

echo json_decode($a == $b);

Another option is var_export() which, despite the name, seems to accept an expression nowadays:

var_export($a == $b); // option one, directly print
echo var_export($a == $b, true); // option 2, get string and print it yourself

Upvotes: 0

Gergo Erdosi
Gergo Erdosi

Reputation: 42028

It doesn't print anything because the result of $a==$b is a boolean, and false is converted to an empty string. Use var_dump instead (if you are debugging your code):

var_dump($a==$b);

Or alternatively you can use echo this way:

echo ($a==$b) ? 'true' : 'false';

Upvotes: 4

Related Questions