Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...