PHP multiple ternary operator not working as expected
Because what you've written is the same as:
echo (true ? 1 : true) ? 2 : 3;
and as you know 1 is evaluated to true
.
What you expect is:
echo (true) ? 1 : (true ? 2 : 3);
So always use braces to avoid such confusions.
As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.
PHP Ternary Operators don't work as expected?
The ternary operator is left associative unlike most other languages such as C#. The code:
$active = is_null($param)
? true
: is_string($param)
? (strtolower($param) === 'true')
: true;
is evaluated as follows:
$active = ((is_null($param) ? true : is_string($param))
? (strtolower($param) === 'true') : true);
You must explicitly add parenthesis to make sure ?:
works the way it does in familiar languages:
$active = is_null($param)
? true
: (is_string($param)
? (strtolower($param) === 'true')
: true);
Stacking Multiple Ternary Operators in PHP
Others have already suggested the right way of doing it but if you really want to use ternary operator you need to use parenthesis as:
$province = 7;
$Myprovince = (
($province == 6) ? "city-1" :
(($province == 7) ? "city-2" :
(($province == 8) ? "city-3" :
(($province == 30) ? "city-4" : "out of borders")))
);
Updated Link
Using nested ternary operators
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;
Conditional ternary operator malfunctions (PHP)
Documentation reads:
Note: It is recommended that you avoid "stacking" ternary expressions.
PHP's behaviour when using more than one ternary operator within a
single statement is non-obvious:
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
PHP ternary operator error
You need to add some parenthesis.
$b = 'a';
$c = 'd';
echo ($b == 'a') ? 2 : ($c == 'a' ? 1 : 0);
ternary multiple conditions with multiple values
About 1
:
In PHP, ||
doesn't do what you might expect coming from JavaScript, because the result will always be a boolean. ||
implicitely converts its operands to booleans and returns the result.
To get the equivalent of a short-circuit ||
from JavaScript in PHP, you can use ?:
(the so-called "Elvis operator" - x ?: y
is a shorthand for x ? x : y
):
$days = isset($dy['value']) || isset($days['value']) ? ($dy['value'] ?: $days['value']) : null;
I didn't change the first ||
because it's indeed a boolean operation, but I did replace the second.
However I think there is a logic error in your code anyway, because if you have E_NOTICE
error reporting on, PHP will complain anyway if $days['value']
is set and $dy['value']
isn't, because you are still accessing $dy['value']
even if isset($dy['value']) == false
. So you would need to use, for example:
$days = (isset($dy['value']) ? $dy['value'] : null) ?: (isset($days['value']) ? $days['value'] : null);
(Assuming you also want to skip a value if it's falsy - according to how you are using the ||
it looks like it.)
If you don't care about notice errors at all (discouraged!) you could just use:
$days = $dy['value'] ?: $days['value'] ?: null;
PHP nested conditional operator bug?
It is recommended that you avoid
"stacking" ternary expressions. PHP's
behaviour when using more than one
ternary operator within a single
statement is non-obvious
From the PHP Manual under "Non-obvious Ternary Behaviour".
Ternary operators are evaluated left to right, so unless you add it the braces it doesn't behave as you expect. The following would work though,
return (true ? "a" : (false ? "b" : "c"));
Related Topics
Symfony2 Create Own Encoder for Storing Password
How to Merge Two Eloquent Collections
PHP Constructor to Return a Null
What Is Salt and How to Use It
Laravel Validation: Exists with Additional Column Condition - Custom Validation Rule
How to Get CSV File to Download on Ie? Works on Firefox
Does the Order of Class Definition Matter in PHP
How to Call a PHP Function from Ajax
Undefined Index While Uploading File
Pass Array Literal to Postgresql Function
How to Validate a Domain Name Using Regex & PHP
How to Pass an Array Using PHP & Ajax to JavaScript
PHP Files Are Downloaded by Browser Instead of Processed by Local Dev Server (Mamp)
Return PHP Object by Index Number (Not Name)
MySQL Query Result in PHP Variable