Question

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:

  • "admin"
  • "edit"
  • "wadmin"
  • "wuser"

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

Was it helpful?

Solution 2

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');

OTHER TIPS

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];
?>

Use nested, i hope help you. You can extend forever ;)

echo $match == "admin" ? "16" : ($match == "edit" ? "12" : ($match == "wadmin" ? "8" : ($match == "wuser" ? "4" : "NONE")));

use parantheses: echo $match == "admin" ? "16" : ($match == "edit" ? "12" : "8");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top