Jump to content

Multiple results using ternary condition


ChadNomad

Recommended Posts

Hey. I've just started using the ternary operator to shorten my code and make it more readable. I'm curious to know if you can have more than one result returned and how (if you can).

 

I've currently got this:

$password == $passwordConfirm ? $valid[3] = 1 : $valid[3] = 0;

 

I'd like to add $vError++ as well in the "else" part if it's possible. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/77926-multiple-results-using-ternary-condition/
Share on other sites

How would you ever "return" more than 1 result.

Do you mean you want to perform more than 1 action per operator section?

e.g.

 

$password == $passwordConfirm ? $valid[3] = 1 AND $valid[7] = true : $valid[3] = 0;

 

(btw the above code is nonsense, before you try it)

 

If you want to do that you need to use an if statement, or two ternary statements.

$result1 = $password == $passwordConfirm ? $valid[3] = 1 : $valid[3] = 0;
$result2 = $password == $passwordConfirm ? $valid[7] = "my var" : $valid[7] = 0;

OR

if($password == $passwordConfirm){
  $valid[3] = 1;
  $valid[7] = "my var";
} else {
  $valid[3] = 0;
  $valid[7] = 0;
}

Do you mean you want to perform more than 1 action per operator section?

e.g.

 

$password == $passwordConfirm ? $valid[3] = 1 AND $valid[7] = true : $valid[3] = 0;

 

(btw the above code is nonsense, before you try it)

 

I did mean that. Also why is it nonsense? AND works fine...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.