Home > Mobile >  PHP: Is there an alternative to using multiple if-statements?
PHP: Is there an alternative to using multiple if-statements?

Time:12-22

I am in the making of some code that needs to check if a users login details are correct, and I therefore need a lot of if-statements inside each other. If any of the conditions in the if-statements are not true, they should alle return the same value. Is there an easy way of doing this, instead of writing the same multiple times? I have made an example below to visualize my problem. As you can see here I write " else { return false; }" multiple time, and this is what I am wondering if you are able to do more efficiently. Maybe so I only have to write "or else return false" once.

//some code
if (/*some condition*/) {
  //some code
  if (/*some new condition*/) {
    //some code
    if (/*some new condition*/) {
        //some code
      } else {
        return false;
      }
   } else {
     return false;
   }
} else {
  return false;
}

I am having a hard time finding a good way to explain my problem, so if you have a more elegant way of explaining it, do not hesitate to edit my post. I am also not quite sure that the title is as good as it could be, so if you have any ideas to an alternativ please say so :)

CodePudding user response:

Lets say you have something like that (I added No):

if ( condition1 ) {
  //some code 1
  if ( condition2 ) {
    //some code 2
    if ( condition3 ) {
        //some code 3
      } else {
        return false;
      }
   } else {
     return false;
   }
} else {
  return false;
}

Since each time a condition is false, you exit the function returning false, you can directly test if the condition is false using a negation (if the negated condition is true):

if ( !condition1 ) {
    return false;
}
//some code 1
if ( !condition2 ) {
    return false;
}
//some code 2
if ( !condition3 ) {
    return false;
}
//some code 3

This doesn't reduce the number of if statements, but you avoid many nesting levels and the else statements.

CodePudding user response:

You can also try the switch statement. For many situations it will produce cleaner code.

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

The switch statement is also compatible with using strings:

<?php
switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}
?>

Good luck! :)

  • Related