View Full Version : Question regarding ternary operator

12-14-2002, 03:32 AM
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 : "";

In JavaScript, the same concept works, so I'm curious why it doesn't in PHP. Basically the logic is to set $inputpass to three different values, depending on whether $test or $test2 is defined.


12-14-2002, 05:18 AM
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 : "");

Also, in Javascript, you could achieve the same like so:

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, 01: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";
echo $inputpass;

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";