John Davidson

php - 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?

My Answer:
You can refactor the code using a switch statement instead of multiple if-else statements. Here's how you can do it:

switch (true) {
case $a:
return $a;
case $b:
return $b;
case $c:
return $c;
return $d;

This way, you can still check the variables in the desired priority order while making the code more readable and maintainable.

Rate this post

3 of 5 based on 7518 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us