Skip to content
Advertisement

refactor IF statement with multiple returns

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?

Advertisement

Answer

You can use a switch / case where the condition is TRUE.

Example:

switch (TRUE) {

  case (isset($a)) : return $a; break;
  case (isset($b)) : return $b; break;
  case (isset($c)) : return $c; break;

  default : return $d;

}

Further Reading:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement