php switch case statement to handle ranges
$str = 'This is a test 123 + 3';
$patterns = array (
'/[a-zA-Z]/' => 10,
'/[0-9]/' => 100,
'/[\+\-\/\*]/' => 250
);
$weight_total = 0;
foreach ($patterns as $pattern => $weight)
{
$weight_total += $weight * preg_match_all ($pattern, $str, $match);;
}
echo $weight_total;
*UPDATE: with default value *
foreach ($patterns as $pattern => $weight)
{
$match_found = preg_match_all ($pattern, $str, $match);
if ($match_found)
{
$weight_total += $weight * $match_found;
}
else
{
$weight_total += 5; // weight by default
}
}
Range in PHPs switch
Understand that your switch statement is comparing the switch value with the expression in each case statement:
if $day = 0
and case $day >= 1 && $day <= 5:
then $day >= 1 && $day <= 5
is false and $day
(from the switch value) loose-type compares to false, so this expression evaluates as true.... and is executed.
switch/case is not a glorified series of if/elseif/else statements..... its a comparison between the defined switch value and the case statement
EDIT
As for your second attempt:
case 1-5
is 1
minus 5
= -4
:
PHP: issue with switch with range
You can do it like this:
$myVar = 50;
switch (true) {
case($myVar < 0):
// do stuff
break;
case($myVar < 10):
// do stuff
break;
case($myVar < 20):
// do stuff
break;
case($myVar < 30):
// do stuff
break;
case($myVar < 999):
// do stuff
break;
default:
// do stuff
break;
}
There are a few good example about that in the comments of the manual.
Using comparison operators in a PHP 'switch' statement
A more general case for solving this problem is:
switch (true) {
case $count <= 20:
$priority = 'low';
break;
case $count <= 40:
$priority = 'medium';
break;
case $count <= 60:
$priority = 'high';
break;
default:
$priority = 'severe';
break;
}
Syntax for case range in C?
This is not possible in standard C, although some compilers offer switching on a range as a compiler extension1.
The idiomatic way in your case is to write
if (number < 1){
// oops
} else if (number <= 5000){
// ToDo
} else if (number <= 10000){
// ToDo
} else if (number <= 15000){
// ToDo
} else {
// oops
}
Or a very crude way would be to write switch((number - 1) / 5000)
which exploits integer division: mapping the cases you need to deal with to 0, 1, and 2.
1 https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
How can I use ranges in a switch case statement using JavaScript?
You have at least four options:
1. List each case
As shown by LightStyle, you can list each case explicitly:
switch(myInterval){
case 0:
case 1:
case 2:
doStuffWithFirstRange();
break;
case 3:
case 4:
case 5:
doStuffWithSecondRange();
break;
case 6:
case 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
2. Use if
/ else if
/ else
If the ranges are large, that gets unwieldy, so you'd want to do ranges. Note that with if...else if...else if
, you don't get to the later ones if an earlier one matches, so you only have to specify the upper bound each time. I'll include the lower bound in /*...*/
for clarity, but normally you would leave it off to avoid introducing a maintenance issue (if you include both boundaries, it's easy to change one and forget to change the other):
if (myInterval < 0) {
// I'm guessing this is an error
}
else if (/* myInterval >= 0 && */ myInterval <= 2){
doStuffWithFirstRange();
}
else if (/* myInterval >= 3 && */ myInterval <= 5) {
doStuffWithSecondRange();
}
else if (/* myInterval >= 6 && */ myInterval <= 7) {
doStuffWithThirdRange();
}
else {
doStuffWithAllOthers();
}
3. Use case
with expressions:
JavaScript is unusual in that you can use expressions in the case
statement, so we can write the if...else if...else if
sequence above as a switch
statement:
switch (true){
case myInterval < 0:
// I'm guessing this is an error
break;
case /* myInterval >= 0 && */ myInterval <= 2:
doStuffWithFirstRange();
break;
case /* myInterval >= 3 && */ myInterval <= 5:
doStuffWithSecondRange();
break;
case /* myInterval >= 6 && */ myInterval <= 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
I'm not advocating that, but it is an option in JavaScript, and there are times it's useful. The case
statements are checked in order against the value you give in the switch
. (And again, lower bounds could be omitted in many cases because they would have matched earlier.) Even though the case
s are processed in source-code order, the default
can appear anywhere (not just at the end) and is only processed if either no case
s matched or a case
matched and fell through to the default (didn't have a break
; it's rare you want to do that, but it happens).
4. Use a dispatch map
If your functions all take the same arguments (and that could be no arguments, or just the same ones), another approach is a dispatch map:
In some setup code:
var dispatcher = {
0: doStuffWithFirstRange,
1: doStuffWithFirstRange,
2: doStuffWithFirstRange,
3: doStuffWithSecondRange,
4: doStuffWithSecondRange,
5: doStuffWithSecondRange,
6: doStuffWithThirdRange,
7: doStuffWithThirdRange
};
Then instead of the switch:
(dispatcher[myInterval] || doStuffWithAllOthers)();
That works by looking up the function to call on the dispatcher
map, defaulting to doStuffWithAllOthers
if there's no entry for that specific myInterval
value using the curiously-powerful ||
operator, and then calling it.
You can break that into two lines to make it a bit clearer:
var f = dispatcher[myInterval] || doStuffWithAllOthers;
f();
I've used an object for maximum flexibility. You could define dispatcher
like this with your specific example:
var dispatcher = [
/* 0-2 */
doStuffWithFirstRange,
doStuffWithFirstRange,
doStuffWithFirstRange,
/* 3-5 */
doStuffWithSecondRange,
doStuffWithSecondRange,
doStuffWithSecondRange,
/* 6-7 */
doStuffWithThirdRange,
doStuffWithThirdRange
];
...but if the values aren't contiguous numbers, it's much clearer to use an object instead.
Related Topics
Preg_Match with International Characters and Accents
How to Force Page Not to Be Cached in PHP
Mysql_Connect (Localhost/127.0.0.1) Slow on Windows Platform
Using Print_R and Var_Dump with Circular Reference
Multi-Dimensional Array Post from Form
Create PHP Array from MySQL Column
PHP Array Printing Using a Loop
Adding Two Time Values of Similar Formats Using PHP
How to Send the Values of an Array of Checkboxes Through Ajax Using Jquery
How to Format a Number to a Dollar Amount in PHP
How to Get the Destination Url Using Curl
Soft Delete Best Practices (Php/Mysql)
How to Convert Utc Datetime to Another Timezone
Global Variables in PHP Not Working as Expected