0

I have code like this can some one help me figure out how the condition logic work in this

$environment = ( $this->environment == "yes" ) ? 'TRUE' : 'FALSE';
    // Decide which URL to post to
      $environment_url = ( "FALSE" == $environment )
                               ? 'https://api.ewaypayments.com/AccessCodes'
               : 'https://api.sandbox.ewaypayments.com/AccessCodes';
  • 2
    Look up how the ternary operator works, [here's](https://davidwalsh.name/php-shorthand-if-else-ternary-operators) a useful link – Ismael Padilla Jun 28 '19 at 22:37
  • 1
    just think an "if" in front of each "(", a "then" for each "?" and an "else" for each ":" – Jeff Jun 28 '19 at 22:40
  • @IsmaelPadilla Thanks –  Jun 28 '19 at 22:42
  • @Jeff that makes it very easy thank you :). Maybe you can make it as an answer? –  Jun 28 '19 at 22:43
  • 1
    Possible duplicate of [Reference — What does this symbol mean in PHP?](https://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Greg Schmidt Jun 29 '19 at 00:55
  • 1
    Someone in your team really takes a lot of extra work to avoid [booleans](https://www.php.net/manual/en/language.types.boolean.php) – Álvaro González Jun 29 '19 at 08:03

2 Answers2

1

You have two ternary if statements. Although they look different than traditional if statements, they operate the same way.

Line by line -- This is how this code works:

$environment = ( $this->environment == "yes" ) ? 'TRUE' : 'FALSE';

This is the exact same as

if($this->environment == "yes"){
    $environment = 'TRUE';
}else{
    $environment = 'FALSE';
}

So now $environment has been set. Onto the next ternary if

$environment_url = ( "FALSE" == $environment )
    ? 'https://api.ewaypayments.com/AccessCodes'
    : 'https://api.sandbox.ewaypayments.com/AccessCodes';

This is the exact same as this if:

if ($environment == 'FALSE'){
    $environment_url = 'https://api.ewaypayments.com/AccessCodes';
}else{
    $environment_url = 'https://api.sandbox.ewaypayments.com/AccessCodes';
}

The ? in the statement indicates to php that this is a ternary conditional. The condition on the left side of the : is what happens if the statement returns "positive". The condition on the right side is what happens if the statement returns "negative".

Zak
  • 6,976
  • 2
  • 26
  • 48
0

Just think an "if" in front of each (, a "then" for each ? and an "else" for each :

It's called tenary operator

Jeff
  • 6,895
  • 1
  • 15
  • 33