0

I have already seen the thread PHP ternary operator error

I have seen the thread mentioned above and am using parenthesis but still it doesn't give the expected output.

<?php
    $ch = 'A';
    $ans = (($ch == 'C') ? 'Cccc'
        : ($ch == 'A') ? 'Aaaa'
        : ($ch == 'G') ? 'Ggggg'
        : ($ch == 'Y') ? 'Yyyyy'
        : 'unknown');
    echo $ans;
    echo "\n";
?>

This outputs Yyyyy and not Aaaa as expected. Can anyone explain why ?

Community
  • 1
  • 1
mrid
  • 5,782
  • 5
  • 28
  • 71
  • 2
    Why don't you just use an associative array instead of a sequence of ternaries? – Barmar Jan 01 '17 at 08:57
  • Thanks for the suggestion @Barmar ! I can use an associative array but I was just curious why this is happening – mrid Jan 01 '17 at 09:05
  • It's because the ternary operator is left-associative. So it's as if you wrote `((($ch == 'C') ? 'Cccc' : ($ch == 'A') ? 'Aaaa' : ($ch == 'G') ? 'Ggggg' : ($ch == 'Y')) ? 'Yyyyy' : 'unknown')` – Barmar Jan 01 '17 at 09:08

1 Answers1

1

The braces is not placed right way. Try this

$ch = 'A';
    $ans = ($ch == 'C' ? 'Cccc' :
         ($ch == 'A' ? 'Aaaa' :
         ($ch == 'G' ? 'Ggggg' : 
         ($ch == 'Y' ? 'Yyyyy':
         'unknown'))));
    echo $ans;
    echo "\n";
Naga
  • 2,190
  • 3
  • 16
  • 21