Chen Li Yong
Chen Li Yong

Reputation: 6087

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.

Upvotes: 4

Views: 94

Answers (3)

devpro
devpro

Reputation: 16117

If you just want check either value exist or not you can use in_array()

If you want to check position of 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

Upvotes: 1

Indrasis Datta
Indrasis Datta

Reputation: 8618

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 */
}

Upvotes: 3

jakub wrona
jakub wrona

Reputation: 2254

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
}

Upvotes: 8

Related Questions