Return statement shorthand syntax [duplicate] - php

This question already has answers here:
What does the question mark and the colon (?: ternary operator) mean in objective-c?
(13 answers)
Closed 8 years ago.
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

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 )
▲ ▲ ▲ ▲
| | | |
\ \_____________________________/ /
\_______________________________________/

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;

It is a shorthand if statement. Consider the following code
$Test = true ? 1 : 3;
// test is 1
$Test = false ? 1 : 3;
// test is 3

Related

How does this nested ternary expression work? [duplicate]

This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I was making a clamp() function in php, and decided to go for a nested ternary expression just to try it.
In the end, I settled with this (working) function :
function clamp($value, $min, $max){
return
$value<$min ? $min
: ($value>$max ? $max
: $value);
}
However, why are the brackets around the second expression required? I had tried removing them afterward :..
function clamp($value, $min, $max){
return
$value<$min ? $min
: $value>$max ? $max
: $value;
}
... but in this version, it will return $max if $value is smaller than $min. I just don't understand how it comes to that result.
I had hear of php having "left associativity" with ternary, though I never understood what it meant:
Take
$bool ? "a" : $bool ? "b" : "c"
Right associativity is: $bool ? "a" : ($bool ? "b" : "c")
Left associativity is : ($bool ? "a" : $bool) ? "b" : "c"
So in the end php will always it evaluate to either b or c.
Bonus:
$bool ? $bool ? "c" : "b" : "a"
Here is a syntax that I think wouldn't change meaning based on associativity.
I wonder whether people managed to find a pretty indentation for this variant.

ternary operator with ampersand [duplicate]

This question already has answers here:
Can you pass by reference while using the ternary operator?
(5 answers)
Closed 7 years ago.
I use followed somewhere in my code:
if (isset($flat[$pid])) {
$branch = &$flat[$pid]['items'];
} else {
$branch = &$tree;
}
All ok, but when I want to short it to:
$branch = isset($flat[$pid]) ? &$flat[$pid]['items'] : &$tree;
I get:
syntax error, unexpected '&' ...
What I'm doing wrong?
This is because the ternary operator is an expression, so it doesn't evaluate to a variable. And a quote from the manual:
Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
This will work as alternative,
(isset($flat[$pid])) ? ($branch = &$flat[$pid]['items']) : ($branch = &$tree);
Edit:
The shortest it can go will be two lines,
#$temp = &$flat[$pid]['items'];
$branch = &${isset($flat[$pid]) ? "temp" : "tree"};

I came across this sign in PHP " ? 0 : ".What does it mean? [duplicate]

This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
This condition was found in this function:
$kValues = getValueCluster($clusters, $data);
foreach($cPos as $k => $position)
{
$cPos[$k] = empty($kValues[$k]) ? 0 : avg($kValues[$k]);
}
return $cPos
I have been trying to find out what this is. I've searched it in google and it has nothing on it.
... ? ... : ... is a ternary operator. It exists in a lot of languages. It's used like that:
variable = test ? assignIfTrue : assignIfFalse;
In your case, $cPos[$k] will be assigned to 0 if $kValues[$k] is empty and to avg($kValues[$k]) if not.
That's PHP's ternary operator.
Basic example:
$x = true;
$y = $x ? 'true!' : 'false';

Difference between $a == 1 and 1 == $a [duplicate]

This question already has answers here:
PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate]
(3 answers)
Closed 8 years ago.
I have seen multiple examples of such comparison, some other example ( from wordpress core):
if ( '' != $qv['subpost'] )
$qv['attachment'] = $qv['subpost'];
Is code above same as:
if ( $qv['subpost'] != '' )
$qv['attachment'] = $qv['subpost'];
or they are different in functionality?
Some people prefer the constant == variable option, as it'll cause fatal errors if you accidentally type a = and try to do assignment:
e.g.
$a = 'foo'; // assigns 'foo' to $a
$a == 'foo'; // tests for equality
'foo' == $a // tests for equality
'foo' = $a // syntax error - assigning value to a string constant
But functionally, otherwise, there's no difference between both versions. a == b is fully equivalent to b == a.
There is no difference.
(A == B) == (B == A)
The only thing that someone can put the value first is the readability, for example:
if ( 'APPLE' == $var ) {
} else if ('BANANA' == $var) {
}
There is no functional difference. You are comparing equality, and they will either be equal or not, no matter what side of the operator the values are on.
This question comes down to code style. Personally, when comparing against static values I prefer to always have the variable on the left. Others disagree. Use whatever style is in place in the project you're working on.
Yes, they do the same thing. It checks to see if $qv['subpost'] contains a value in both examples. No difference at all unless you're Yoda.

PHP Programming Syntax Question 'x ? x : x;' [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the PHP ? : operator called and what does it do?
I've been programming PHP for years, but have never understood what this syntax does or means. I'm hoping you guys can explain it to me, it's about time I knew the answer:
list($name, $operator) = (strpos($key, '__')) ? explode('__', $key) : array($key, null);
Specifically, I'm curious about the SOMETHING ? SOMETHING : SOMETHING;
It's shorthand for if() { } else {}.
if($i == 0) {
echo 'hello';
} else {
echo 'byebye';
}
is the same as:
echo $i == 0 ? 'hello' : 'byebye';
The first statement after '?' is executed if the first expression before '?' is true, if not the last is executed. It also evaluates to the value of the executed expression.
Its conditional operator just like if in simple words if in one line
(condition) ? statement1 : statement2
If condition is true then execute statement1 else statement2
this is the pure if else tertiary operation
if(a==b) {
c = 3;
} else {
c = 4;
}
this is same as
c = (a==b) ? 3:4;

Categories