Using nested ternary operators

As of PHP 7 we can use Null coalescing operator

$selectedTemplate = $_POST['selectedTemplate'] ?? $_GET['selectedTemplate'] ?? 0;

It's simpler to read if we write ternary in the following manner:

$myvar = ($x == $y)
  ?(($x == $z)?'both':'foo')
  :(($x == $z)?'bar':'none');

But ternary operators are short, effective ways to write simple if statements. They are not built for nesting. :)


A little investigate here, and I guess, I've found real answer :)

Example code:

<?php

$test = array();
$test['a'] = "value";


var_dump(
    isset($test['a'])
        ? $test['a']
        : isset($test['b'])
            ? $test['b']
            : "default"
);

Be attentive to round brackets, that I've put.

I guess, you're waiting to get similar behavior:

var_dump(
    isset($test['a'])
        ? $test['a']
        : (isset($test['b'])  // <--  here
            ? $test['b']
            : "default")      // <--  and here
);

But! Real behavior looks like this:

var_dump(
    (isset($test['a'])        // <--  here
        ? $test['a']
        : isset($test['b']))  // <--  and here
            ? $test['b']
            : "default"
);

General mistake was, that you've missed notice: Undefined index.

Online shell.


Wrap it in parentheses:

$selectedTemplate = isset($_POST['selectedTemplate'])
                  ? $_POST['selectedTemplate']
                  : (
                       isset($_GET['selectedTemplate'])
                       ? $_GET['selectedTemplate']
                       : 0
                  );

Or even better, use a proper if/else statement (for maintainability):

$selectTemplate = 0;

if (isset($_POST['selectedTemplate'])) {
    $selectTemplate = $_POST['selectedTemplate'];
} elseif (isset($_GET['selectedTemplate'])) {
    $selectTemplate = $_GET['selectedTemplate'];
}

However, as others have pointed out: it would simply be easier for you to use $_REQUEST:

$selectedTemplate = isset($_REQUEST['selectedTemplate'])
                  ? $_REQUEST['selectedTemplate']
                  : 0;

Tags:

Php