Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any equivalent of SQL IN (…) query in Laravel for multiple if condition?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading