Ternary operator with ampersand

I use somewhere in my code:

if (isset($flat[$pid])) { $branch = &$flat[$pid]['items']; } else { $branch = &$tree; } 

Everything is fine, but when I want it briefly:

 $branch = isset($flat[$pid]) ? &$flat[$pid]['items'] : &$tree; 

I get:

syntax error, unexpected '&' ...

What am I doing wrong?

+5
source share
2 answers

This is because the ternary operator is an expression, so it does not evaluate the variable. And a quote from the manual:

Note: Please note that the ternary operator is an expression and that it does not evaluate the variable , but the result of the expression. It is important to know if you want to return the variable by reference. The operator returns $ var == 42? $ a: $ b; therefore, the return-by-reference function will not work and a warning will be issued in later versions of PHP.

+8
source

It will work as an alternative,

 (isset($flat[$pid])) ? ($branch = &$flat[$pid]['items']) : ($branch = &$tree); 

Edit:

The shortest thing that can pass is two lines,

 @$temp = &$flat[$pid]['items']; $branch = &${isset($flat[$pid]) ? "temp" : "tree"}; 
+1
source

All Articles