Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php switch case statement to handle ranges

I'm parsing some text and calculating the weight based on some rules. All the characters have the same weight. This would make the switch statement really long can I use ranges in the case statement.

I saw one of the answers advocating associative arrays.

$weights = array( [a-z][A-Z] => 10, [0-9] => 100, ['+','-','/','*'] => 250 ); //there are more rules which have been left out for the sake of clarity and brevity $total_weight = 0; foreach ($text as $character) {   $total_weight += $weight[$character]; } echo $weight; 

What is the best way to achieve something like this? Is there something similar to the bash case statement in php? Surely writing down each individual character in either the associative array or the switch statement can't be the most elegant solution or is it the only alternative?

like image 204
nikhil Avatar asked Jan 16 '12 06:01

nikhil


People also ask

Can we use range in switch case?

You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

Can we use condition in switch case PHP?

Each condition you want to match has a case where you pass in the variable you want to match. Within the case, you put the code you want to run if the condition matches. Then you need to add a break, otherwise the code will continue to check for matches in the rest of the switch statement.

How do you use condition in a switch case?

In a switch statement, we pass a variable holding a value in the statement. If the condition is matching to the value, the code under the condition is executed. The condition is represented by a keyword case, followed by the value which can be a character or an integer. After this, there is a colon.

Which is faster switch case or if else in PHP?

Speed: A switch statement might prove to be faster than ifs provided number of cases are good.


1 Answers

Well, you can have ranges in switch statement like:

//just an example, though $t = "2000"; switch (true) {   case  ($t < "1000"):     alert("t is less than 1000");   break   case  ($t < "1801"):     alert("t is less than 1801");   break   default:     alert("t is greater than 1800") }  //OR switch(true) {    case in_array($t, range(0,20)): //the range from range of 0-20       echo "1";    break;    case in_array($t, range(21,40)): //range of 21-40       echo "2";    break; } 
like image 171
Sudhir Bastakoti Avatar answered Sep 21 '22 07:09

Sudhir Bastakoti