0

I am new to php developing but so far have been able to do whatever I want. I recently came across a strange syntax of writing a return statement:

public static function return_taxonomy_field_value( $value )
{ 
   return (! empty(self::$settings['tax_value']) ) ? self::$settings['tax_value'] : $value;
}

I get the return() and the !empty() but after that it has a ? and that's where I get lost. Any help is much appreciated! Thanks guys

bosnjak
  • 8,424
  • 2
  • 21
  • 47
user3455992
  • 101
  • 1
  • 9
  • You should mention in the Question title or in the tag (not just in the question text) that you are talking about PHP :) – Morten Jensen Mar 24 '14 at 15:16
  • 1
    It's called a "ternary" operator. [http://php.net/ternary](http://php.net/ternary#language.operators.comparison.ternary). `return a ? b : c;` is shorthand for `if(a) { return b; } else{ return c; }`. – gen_Eric Mar 24 '14 at 15:18

3 Answers3

3

This is a ternary operator, a short version of the if statement.

This:

$a = $test ? $b : $c;

is the same as:

if($test)
{
    $a=$b;
}
else
{
    $a=$c;
}

so basically your example is equivalent to:

if(! empty(self::$settings['tax_value'])
{
    return self::$settings['tax_value'];
}
else
{
    return $value;
}

You can find some more info here, together with some tips for precautions when using ternary operators.

Important note about the difference from other languages

Since the question is marked as a duplicate of another question that deals with ternary operator in Objective-C, I feel this difference needs to be addressed.

The ternary operator in PHP has a different associativity than the one in C language (and all others as far as I know). To illustrate this, consider the following example:

$val = "B";
$choice = ( ($val == "A") ? 1 : ($val == "B") ? 2 : ($val == "C") ? 3 : 0 );
echo $choice;

The result of this code (in PHP) will be 3, even though it would seem that 2 should be the correct answer. This is due to weird associativity implementation that threats the upper expression as:

( ( ( ($val=="A") ? 1 : ($val=="B") ) ? 2 : ) ($val=="C") ? 3 : 0 )  
  ▲ ▲                               ▲       ▲  
  | |                               |       |  
  \  \_____________________________/        /  
   \_______________________________________/  
bosnjak
  • 8,424
  • 2
  • 21
  • 47
0

This is called the ternary operator - have a look here

This basically translates to [statement] ? [true execution path] : [false execution path]

In your case, this would do the following:

if(! empty(self::$settings['tax_value']) ) 
    return self::$settings['tax_value'];
else 
    return $value;
ElGauchooo
  • 4,256
  • 2
  • 13
  • 16
0

It is a shorthand if statement. Consider the following code

$Test = true ? 1 : 3;
//  test is 1
$Test = false ? 1 : 3;
//  test is 3
ug_
  • 11,267
  • 2
  • 35
  • 52