-2

Hi I am trying to modify this line of php and add two further values to it

$my_role = ( $user == "AS") ? 8 : 10;

I would like to add the values 16 and 17

I tried

$my_role = ( $user == "AS") ? 8 : 10 : 16 : 17;

but this results in a

syntax error, unexpected ':'

Can anyone help please?

UPDATE: Thanks for your comments - Yes i managed to find out this was a ternary operator and that adding further values to it was nonsensical - What are the PHP operators "?" and ":" called and what do they do?

OnTarget
  • 61
  • 8
  • 1
    What does this line of code do `$my_role = ( $user == "AS") ? 8 : 10`? – Salman A Jun 17 '21 at 13:15
  • Please share more details. What do you want to achieve? – Nico Haase Jun 17 '21 at 13:15
  • 3
    Well, of course, you're trying to turn a ternary into something else. The original code assigns 8 if the user is AS, otherwise it's 10. Figure out your logic for the rest of the values, and then I'd suggest using an if/elseif/else structure to make it more readable. – aynber Jun 17 '21 at 13:16
  • I'm pretty sure you don't realize what this line does. If $user == "AS" then $my_role will be 8, otherwise be 10 – Timberman Jun 17 '21 at 13:17
  • 5
    `add two further values to it`...for what purpose? It's not clear what you want the outcome to be. Your original code is a [ternary operator](https://www.codementor.io/@sayantinideb/ternary-operator-in-php-how-to-use-the-php-ternary-operator-x0ubd3po6) - basically a short version of an if/else statement. it can only have two outcomes. In your example, the possible outcomes are 8 or 10, depending on whether $user equals "AS" or not. It's not clear how you expect to add two more values and have it still make sense... in what situation would you expect those to be used? It doesn't make sense. – ADyson Jun 17 '21 at 13:17
  • 2
    ...I can only assume you've completely misunderstood the purpose and function of the original line of code. – ADyson Jun 17 '21 at 13:18
  • 1
    Thanks for your comments - yes i managed to find out this was a ternary operator and that adding further values to it was nonsensical - https://stackoverflow.com/questions/1080247/what-are-the-php-operators-and-called-and-what-do-they-do – OnTarget Jun 17 '21 at 13:27

1 Answers1

1

The expression $my_role = ( $user == "AS") ? 8 : 10; is a ternary expression, which is equivalent to the following code:

if($user == "AS") {
   $my_role = 8;
} else {
   $my_role = 10;
}

In that context, $my_role = ( $user == "AS") ? 8 : 10 : 16 : 17; or "add two further values" don't mean anything.

Clément Cartier
  • 174
  • 2
  • 11