php switch case statement to handle ranges

nikhil picture nikhil · Jan 16, 2012 · Viewed 62k times · Source

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?

Answer

Sudhir Bastakoti picture Sudhir Bastakoti · Jan 16, 2012

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;
}