Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator with ampersand [duplicate]

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?

like image 762
vp_arth Avatar asked Dec 24 '22 17:12

vp_arth


1 Answers

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.

like image 113
Rizier123 Avatar answered Jan 07 '23 03:01

Rizier123