Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any syntax or command in php to check whether a number is in a set of numbers?

I come from another language, so I miss this feature on php. For example, if I want to check whether if a number is 2, 4, between 7 to 10, or 15, I would like to express it as:

if ($x in [2, 4, 7...10, 15]) { do_something(); }

Instead of:

if ($x == 2 || $x == 4 || ($x >= 7 && $x <= 10) || $x == 15) { do_something(); }

Or:

switch ($x) {
case 2:
case 4:
case 7:
case 8:
case 9:
case 10:
case 15:
    do_something();
    break;
}

Or even:

switch (true) {
case ($x == 2):
case ($x == 4):
case ($x >= 7 && $x <= 10):
case ($x == 15):
    do_something();
    break;
}

Is there any way in php to do that or workaround similar to that? I use this comparison a lot in my code, and the "in set" format makes my code much more readable and less error-prone (writing 7...10 is safer than writing x >= 7 && x <= 10). Thanks.

like image 929
Chen Li Yong Avatar asked Dec 15 '22 03:12

Chen Li Yong


2 Answers

You may use in_array() for this:

if (in_array(3, [1, 2, 3, 7, 8, 9, 10, 15])) { 
    do_something(); //true, so will do
}
like image 136
jakub wrona Avatar answered Dec 22 '22 00:12

jakub wrona


It's very much possible to specify the range. Use range() function here.

range - Create an array containing a range of elements

$values = range(7, 10); // All values from 7 to 10 i.e 7, 8, 9, 10
$values = array_merge($values, [2, 4, 15]); // Merge your other values

if (in_array(3, $values)) { 
    /* Statements */
}
like image 41
Object Manipulator Avatar answered Dec 21 '22 23:12

Object Manipulator