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

I came from a different language, so I skipped this function in php. For example, if I want to check if there is a number 2, 4, from 7 to 10 or 15, I would like to express it as:

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

Instead:

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 a way in php to do this or a workaround like this? I often use this comparison in my code, and the “bundled” format makes my code more readable and less error prone (writing 7...10is safer than writing x >= 7 && x <= 10). Thank.

+4
source share
3 answers

. range() .

. , .

$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 */
}
+3

in_array() :

if (in_array(3, [1, 2, 3, 7, 8, 9, 10, 15])) { 
    do_something(); //true, so will do
}
+8

If you just need to check if any value exists, you can use in_array()

If you want to check the position of a value than you can use array_search()

$arr = array(1,2,3); 
var_dump(in_array(3, $arr)); // return true 

var_dump(array_search(3, $arr)); // return 2
+1
source

Source: https://habr.com/ru/post/1656452/


All Articles