Reputation: 25372
I know that it is possible to nest ternary operators, and I want to use them in this case to save time (at least in the future).
I have a variable that will hold one of four values:
Each of these is used to determine necessary password lengths based on the user type, 16, 12, 8, and 8, respectively.
I want PHP to echo each of those numbers based on the contents of the variable, in this case named $match
What I have so far is this:
echo $match == "admin" ? "16" : $match == "edit" ? "12" : "8";
But this always echoes 12. How can I rewrite this to properly echo "16", "12", or "8"?
Upvotes: 0
Views: 102
Reputation: 169543
Although it doesn't directly answer the question, you could avoid the nested-ternary entirely:
<?php
$minlen = array(
"admin" => 16,
"edit" => 12,
"wadmin" => 8,
"wuser" => 8,
);
// Example usage
$match = "admin";
echo $minlen[$match];
?>
Upvotes: 4
Reputation: 521
use parantheses:
echo $match == "admin" ? "16" : ($match == "edit" ? "12" : "8");
Upvotes: 0
Reputation: 10717
Use nested, i hope help you. You can extend forever ;)
echo $match == "admin" ? "16" : ($match == "edit" ? "12" : ($match == "wadmin" ? "8" : ($match == "wuser" ? "4" : "NONE")));
Upvotes: 0
Reputation: 57105
This will do the trick.
enclose the false
condition in brackets / parentheses
echo ($match == 'admin') ? '16' : (($match == 'edit') ? '12' : '8');
or
echo $match == 'admin' ? '16' : ($match == 'edit' ? '12' : '8');
Upvotes: 1