Using nested ternary operators [duplicate]

I've been trying to use isset() in nested form like below:

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

But seems I'm missing something. Can anyone assist me how to do it?


Solution 1:

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;

Solution 2:

As of PHP 7 we can use Null coalescing operator

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

Solution 3:

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.