skip to Main Content

I’m having trouble understanding why my PHP code returns "three" instead of "two". Here’s the code:

php
<?php $a = 2; echo $a == 1 ? "one" : $a == 2 ? "two" : $a == 3 ? "three" : "others"; ?>

When I run this in PHP versions earlier than 5.3, the output is "three". Can someone explain why this happens and how the code works?

2

Answers


  1. Your code is quite unreadable, it hurts my brain. Make it readable and you probably also solve any problems you have.

    How about this:

    
    $number = 2;
    
    switch ($number) {
       case 1 : echo "one"; break;
       case 2 : echo "two"; break;
       case 3 : echo "three"; break;
       default : echo "others"; break;
    }
    

    This code is readable and, may I say, slightly more performant.

    There are also many other ways of doing it. Anything is better than multiple ternary operators on one line.

    Login or Signup to reply.
  2. The ternary in PHP works in other direction compared to other programming languages.

    echo $a == 1 ? "one" : $a == 2 ? "two" : $a == 3 ? "three" : "others";
    

    is the same as

    echo (( $a == 1 ? "one" : $a == 2 ) ? "two" : $a == 3 ) ? "three" : "others";
    

    This can be reduced to CONDITION ? "three" : "others" where CONDITION is (( $a == 1 ? "one" : $a == 2 ) ? "two" : $a == 3 ). And CONDITION is always true.

    Compared to other programing languages, I think you want

    echo $a == 1 ? "one" :( $a == 2 ? "two" :( $a == 3 ? "three" : "others"));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search