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"};
Related
This question already has answers here:
corresponding nested ternary operator in php? [duplicate]
(2 answers)
Closed 6 years ago.
getting 2 different outputs while using the same currency 'egp'
$currency = ($q->currency == 'egp')? '£' : (($q->currency == 'usd') ? '$' : '€');
this line outputs $
$currency = ($q->currency == 'egp')? '£' : ($q->currency == 'usd') ? '$' : '€';
this one outputs £
and I can't find why?
note: the only difference is the () around the second ternary operator statement
Consider this code:
echo (true?"Left is first":(true?"Right is first":""));
Left is first
Versus
echo (true?"Left is first":true?"Right is first":"");
Right is first
The exaplanation can be found at http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary.
In short, in the second case PHP will evaluate true?"Left is first":true as the condition for the ternary expression. This will evaluate to Left is first which evaluates to true and therefore Right is first will be echoed
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';
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
'AND' vs '&&' as operator
Sorry for very basic question but I started learning PHP just a week ago & couldn't find an answer to this question on google/stackoverflow.
I went through below program:
$one = true;
$two = null;
$a = isset($one) && isset($two);
$b = isset($one) and isset($two);
echo $a.'<br>';
echo $b;
Its output is:
false
true
I read &&/and are same. How is the result different for both of them? Can someone tell the real reason please?
The reason is operator precedence. Among three operators you used &&, and & =, precedence order is
&&
=
and
So $a in your program calculated as expected but for $b, statement $b = isset($one) was calculated first, giving unexpected result. It can be fixed as follow.
$b = (isset($one) and isset($two));
Thats how the grouping of operator takes place
$one = true;
$two = null;
$a = (isset($one) && isset($two));
($b = isset($one)) and isset($two);
echo $a.'<br>';
echo $b;
Thats why its returning false for first and true for second.
Please see:
http://www.php.net/manual/en/language.operators.logical.php
It explains that "and" is different from "&&" in that the order of operations is different. Assignment happens first in that case. So if you were to do:
$b = (isset($one) and isset($two));
You'd end up with the expected result.
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;