Reputation: 13673
I wonder if I can make a single-line ternary operator that checks the value returned by a function, and uses it?
Let's check this example (PHP) code:
return get_db_row($sql_parameters) ? get_db_row($sql_parameters) : get_empty_row();
my purpose is to return get_db_row()
, but if it is empty, then return an empty row.
But, I think, this line will call get_db_row()
twice. Is it right ?
I want to call it once. One solution could be storing the return value in a variable like this:
$row = get_db_row($sql_parameters);
return $row ? $row : get_empty_row();
But can I do this in one line?
Something like :
return ($row = get_db_row()) ? $row : get_empty_row();
is it possible ?
Thanks for any help !
Upvotes: 0
Views: 130
Reputation: 76636
You have it correct. The following line will only call the function once:
return ($row = get_db_row()) ? $row : get_empty_row();
Some code to prove this:
$counter = 0;
function test() {
global $counter;
$counter++;
return true;
}
$var = ($ret = test()) ? $ret : 'bar';
echo sprintf("#1 called the function %d times\n", $counter);
$counter = 0;
$var = ($ret = test()) ? test() : 'bar';
echo sprintf("#2 called the function %d times", $counter);
Outputs:
#1 called the function 1 times
#2 called the function 2 times
Upvotes: 3
Reputation: 324750
return get_db_row($sql_parameters) ?: get_empty_row();
If you're running an earlier version of PHP that doesn't support this...
return ($x = get_db_row($sql_parameters)) ? $x : get_empty_row();
Should work just fine.
Upvotes: 0