Home > front end >  Is there any equivalent of SQL IN (...) query in Laravel for multiple if condition?
Is there any equivalent of SQL IN (...) query in Laravel for multiple if condition?

Time:07-29

Using laravel, I'm making an if with many || conditions, and I have to write the same syntaxes over and over.

My code example:

if (type == 1 ||  type == 2 || type == 3 || type == 4){
    // my code
}

Is there any shorthand syntax for this? Maybe like an IN operator in SQL.

IF type IN (1, 2, 3, 4)

CodePudding user response:

You could use PHPs in array function https://www.php.net/manual/en/function.in-array.php

$arr = [1, 2, 3, 4];

if (in_array($type, $arr) {

}

If you have multiple groups of values to compare to, use switch()

switch($type) {
    case 1:
    case 2:
    case 3:
    case 4:
        echo 'group 1';
        break;
    case 6:
    case 7:
    case 8:
        echo 'group 2';
        break;
    default:
        echo 'no group found';
        break;
}
  • Related