refactor IF statement with multiple returns

Viewed 346

I have a code similar to this:

if($a) {
  return $a;
} elseif($b) {
  return $b;
} elseif($c) {
  return $c;
} else {
  return $d;
} 

it is honestly not so looking good but I need to check the variables to respect some sort of priority order. I was guessing if there is a better way to write this?

2 Answers

You can use the Null Coalescing Operator:

return $a ?? $b ?? $c ?? $d;

Note that below version 7.0 of PHP this operator is not supported.

As berend pointed out in a comment this does differ slightly from the code in your question. If $a is FALSE then it is defined and will be returned. If that's not what you want, you could fall back on the Ternary Operator:

return isset($a) ? $a : (isset($b) ? $b : (isset($c) ? $c : $d));

but in most usage cases the Null Coalescing Operator will do.

Related