Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nested ternary operators [duplicate]

Tags:

php

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?

like image 372
sikas Avatar asked Jan 04 '12 22:01

sikas


People also ask

Should you use nested ternary operator?

JavaScript static code analysis: Ternary operators should not be nested.

Can you have nested ternary operators?

Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.

What is nested ternary operator?

Ternary operators can be nested just like if-else statements. Consider the following code: int a = 1, b = 2, ans; if (a == 1) { if (b == 2) { ans = 3; } else { ans = 5; } } else { ans = 0; } printf ("%d\n", ans); Here's the code above rewritten using a nested ternary operator: int a = 1, b = 2, ans; ans = (a == 1 ? (

How do you perform multiple operations in a ternary operator?

You can use the comma operator to execute multiple expressions in place of a single expression: arr[i] % 2 === 0? (evenCount++, totalCount++) : (oddCount++, totalCount++); The result of the comma operator is the result of the last expression.


2 Answers

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; 
like image 50
Joseph Silber Avatar answered Oct 04 '22 03:10

Joseph Silber


As of PHP 7 we can use Null coalescing operator

$selectedTemplate = $_POST['selectedTemplate'] ?? $_GET['selectedTemplate'] ?? 0; 
like image 22
Adersh Avatar answered Oct 04 '22 02:10

Adersh