php switch case statement to handle ranges

空扰寡人 提交于 2019-11-27 13:03:35
$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
    }
}
Sudhir Bastakoti

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

You can specify the character range using regular expression. This saves from writing a really long switch case list. For example,

function find_weight($ch, $arr) {
    foreach ($arr as $pat => $weight) {
        if (preg_match($pat, $ch)) {
            return $weight;
        }   
    }   
    return 0;
}

$weights = array(
'/[a-zA-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;
$text = 'a1-';
foreach (str_split($text) as $character)
{
  $total_weight += find_weight($character, $weights);
}
echo $total_weight; //360

I think I would do it in a simple way.

switch($t = 100){
    case ($t > 99 && $t < 101):
        doSomething();
        break;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!