Ternary if() elseif() else

Isn’t this the correct syntax for a shorthand if() elseif() else:


$var = (($action == 'edit') ? 'Edit' : ($action == 'delete') ? 'Delete' : 'New');

I have a page where $_GET[‘mode’] can equal ‘edit’ or ‘delete’
Then I call:


$action = (isset($_GET['mode']) ? $_GET['mode'] : 'insert');

Whether or not $_GET[‘mode’] equals ‘edit’ or ‘delete’, $var above never equals ‘Edit’…

Hi tictike,
this code is fine. You just have to print the $action variable and pass mode=edit or delete in the querystring. It is showing the right thing to me.


echo $action = (isset($_GET['mode']) ? $_GET['mode'] : 'insert');

It’s very important where you place parenthesis in nested ternary operators. Basically if you want a nest a ternary operator in an existing ternary operator you need to put parentheses around the whole thing your nesting.

$a ? $b : ( $c ? $d : ( $e ? $f : $g ) )

The following should work “as planned” :


$var = $action == 'edit' ? 'Edit' : ($action == 'delete' ? 'Delete' : 'New');

:slight_smile: