Warm tip: This article is reproduced from stackoverflow.com, please click
php echo return-value ternary-operator conditional-operator

How does the 'Ternary Operator' i.e. the 'conditional operator' work with the 'echo' statement since

发布于 2020-03-27 10:24:32

I'm using PHP 7.3.6 on my laptop that runs on Windows 10 Home Single Language 64-bit operating system.

I've installed the latest version of XAMPP installer on my laptop which has installed the Apache/2.4.39 (Win64) and PHP 7.3.6

Today, I come across following code example from the PHP Manual :

<?php
  echo $some_var ? 'true': 'false'; // changing the statement around
?>

As per my knowledge and according to the following text from PHP Manual :

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

It's also a well-known fact that echo statement in PHP doesn't return any value.

So, in the code example mentioned above also echo statement must not be returning any value.

So, my question is as the echo statement never returns any value how does the ternary operator comes to know that expr1(i.e. the statement echo $some_var) has been evaluated to true or false and accordingly prints the output as true or false?

Questioner
PHPGeek
Viewed
135
treyBake 2019-07-03 22:46

you're reading the logic incorrectly. Which is why I like brackets for my ternary statements. Your ternary is the same as:

if ($some_var) {
    echo 'true';
} else {
    echo 'false';
}

the echo isn't being used in the conditional. If we change the ternary to this, things are clearer:

echo ($some_var ? 'true' : 'false');

this can be seen as echo (if ($some_var) {true} else {false}) (from a logic point of view at least)

So it's not the echo that's being tested, it's the bit before the ? - that's the if statement conditional, not the echo