What could be the result of an echo ("Truth"? (True? 'T': 'f'): "False"); And explain why?

Possible duplicate:
What is PHP ?: the called operator and what does it do?

I tested a very simple PHP question that looked like:

echo ('True'?(true?'t':'f'):'False'); 

Can someone explain the details of the output he will give?

thanks

+4
source share
7 answers

This will reflect t .

First, it checks the first condition, which will give true. and then in the next condition it returns true again and fulfills the first condition t .

In the if and else condition, it will be written as follows:

 if('True') { //condition true and go to in this block if(true){ //condition true and go to in this block echo 't'; // echo t } else { echo 'f'; } } else { echo 'False'; } 
+4
source

Looking at this version, it should be clear:

 if('True'){ // evaluates true if(true){ // evaluates tre echo 't'; // is echo'd }else{ echo 'f'; } }else { echo 'False'; } 
+4
source

A non-empty string is considered to be a true value, except for the string "0" . PHP evaluates the expression from left to right as follows:

  • The expression 'True' evaluates to a boolean value of true
  • Next, the expression following ?
    • The expression true is ... true!
    • Returns the expression following ? which t

Surprisingly, you still get t if the expression:

 echo ('False'?(true?'t':'f'):'False'); 
+4
source

How 'True' evaluates to true

 if('True'){ if(true){ echo 't'; }else{ echo 'f'; } }else{ echo 'False'; } 
+3
source

Will the inner bracket be executed first true?'t':'f' , it will return 't', which is a string

Now the external condition will be checked for echo ('True' ? 't' : 'False') . Here 'True' is a "non-empty string" (implicitly passed to TRUE), so it evaluates to true and returns "t".

The final code will be echo ('t') , which will just display t

+3
source
 echo ( // will echo the output 'True'? // first ternary operation 'True' is considered true (true? 't':'f') // will go here for the second ternary operation // true is also evaluated as true so it will echo 't' : 'False'); // never goes here 
+3
source

It:

 'True'?(true?'t':'f'):'False' 

May be written as

 // Will always be true if String is not an Empty string. if('True'){ // if (true) will always enter if(true){ // t will be the output echo 't'; }else{ echo 'f'; } else { echo 'False'; } 
+3
source

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


All Articles