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.
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
}
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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With