View Full Version : Question regarding ternary operator
Is it possible to use more than 2 expressions in a ternary operator in PHP? Apparently the below, with 3 expressions, doesn't work when I tried it:
$inputpass=isset($test)? $test : isset($test2)? $test2 : "";
Perhaps you should use parentheses?
There might be a different precedence of this operator in PHP than in JS:
$inputpass = isset($test)? $test : (isset($test2)? $test2 : "");
inputpass = test || test2 || '';
You might be able to utilize short-circuit validation in this case too if PHP treats undefined variables (I'm assuming that's what isset checks) as boolean false when typecasted.
12-14-2002, 12:33 PM
jdk hit the nail on the head. Though I'm not quite sure if it's really the precedence of the operators, because this code
$test1 = "test1";
$test2 = "test2";
$inputpass = isset($test1) ? ($test1) : isset($test2) ? $test2 : "default";
prints "test2", and I've expected "test1". Seems to be rather a weirdness of the expression evaluation, since it looks like the innermost ternary operator construct is evaluated first... hmh, I'm not quite satisfied with this explanation, because adding parentheses like jkd suggested solves that problem... strange indeed.
P.S: I couldn't get that JS code to work if both tested variables did not exist (I got an "test is undefined" error). It worked ok with this adjustment:
inputpass = window.test1 || window.test2 || "default";
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.