Shortened conditioning in PHP

Hello, I am very new to programming and in the following exercise, I don’t know why, from the beginning, true="1"

Would would this be?

This is the exercise:

$var = true ? “1” : false ? “2” : “3” ;

The solution is 2 (I already calculated it) but I don’t understand why in the start, true=1, Maybe 1 always equivalent to true by principle in programming?

1 Like

yes - in many weakly typed languages.

1 Like

actually its interesting you code return 2 but your code is just a short version of

if(true){
   $var2 = "1";
}else{
    if(false){
        $var2 = "2";
    }else{
        $var2 = "3";
    }
}

and the long version set $var2 to 1, which makes sense, because true is true, i wonder why the short version return 2

1 Like

It is due to order of operations/execution.

As changing that short-hand version to

$var = true ? "1" : (false ? "2" : "3");

Produces the correct output.

3 Likes

Can you please elaborate more \ expand your answer ?

In “Due to order of operations” you mean that since it’s the first condition (1/2) it’s 1 ?

Because it processes ternary operations from left to right.

I also found this source:

Which has this gem

(not sure if this applies to the article you are working with @s_molinari, or if it would be any use)

In fact, I’m sure that it is processing them left to right. So let’s take your initial code and break it down.

$var = true ? “1” : false ? “2” : “3” ;

PHP’s first process of this statement resembles

$var = (true ? “1” : false) ? “2” : “3” ;

See the problem? Since it seems that first part as the first expression, it then comes up with

$var = (“1”) ? “2” : “3” ;

And we know PHP treats “1” as true, along with 1, and true. So it then assigns “2” to $var.

Edit: There is also a note about it on the PHP Docs.

This might help some

http://php.net/manual/en/language.operators.comparison.php

Note:

It is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #4 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is ‘t’
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? ‘true’ : false) ? ‘t’ : ‘f’);

// here, you can see that the first expression is evaluated to ‘true’, which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Not sure either, but thanks for thinking about the project.

Scott

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.