1

I am trying to stack ternary expressions for this script but i keep getting unexpected ')'

Here is my script

$uri = 9;
$build_status = 20;

/**
Using Ifs
*/
if($uri == 20)
{
echo 'ci=>passing';
}
if($uri < 20 && $uri > 10 && $uri != $build_status)
{
echo "ci=>almost failing";
}
if($uri < 20 && $uri > 18 && $uri != $build_status)
{
echo "ci=>test your code!";
}
elseif($uri < 5)
{
echo "ci=>failed.";
}

/**
Stacking
*/
echo (($uri==20 ? 'ci=>passing') ? ($uri < 20 && $uri > 10 && $uri != $build_status) : 'ci=>almost failing') ;

Where am i going wrong?

  • `Where am i going wrong?` the very idea of replacing readable if blocks with one liners is wrong. – dev-null-dweller Jun 23 '13 at 16:57
  • > Where am i going wrong? This: Never, ever, ever, ever stack ternary expressions. "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ([source](http://stackoverflow.com/questions/876089/who-wrote-this-programing-saying-always-code-as-if-the-guy-who-ends-up-maintai)). And there's a syntax error, too. – Denis de Bernardy Jun 23 '13 at 16:57

2 Answers2

2

($uri==20 ? 'ci=>passing') is a syntax error. You need the : inside the parens.

+1 to the comment about stacking ternary expression. This is even more relevant to PHP because the parser is horribly broken with regard to nested ternary expressions.

mzedeler
  • 4,177
  • 4
  • 28
  • 41
  • There is an interesting read on how broken the ternary ``?``-operator is in PHP here: http://stackoverflow.com/questions/13142538/strange-behaviour-ternary-operator – mzedeler Jun 23 '13 at 18:33
2
echo ($uri==20 ? 'ci=>passing' : 
     ($uri < 20 && $uri > 10 && $uri != $build_status ? 'ci=>almost failing' :
     ($uri < 20 && $uri > 18 && $uri != $build_status ? 'ci=>test your code!' :
     ($uri < 5 ? 'ci=>failed.' : "[doesn't match previous conditions]"
))));

In majority of languages parentheses are optional but php requires them as ternary operator is left-associative http://www.phpsadness.com/sad/30

mpapec
  • 50,217
  • 8
  • 67
  • 127