简体   繁体   中英

Converting a nested if-else based on range condition into switch statement

How can I convert following long if-else condition into switch case in PHP? Or, please suggest any feasible solution besides switch case.

if($total_products >= 1 && $total_products <=10 ){

} elseif ($total_products >= 11 && $total_products <=25 ){

} elseif ($total_products >= 26 && $total_products <=40 ){

} elseif ($total_products >= 181 && $total_products <=200 ){

} elseif ($total_products >= 351 && $total_products <=400 ){

} elseif ($total_products >= 401 && $total_products <=500 ){

} elseif ($total_products > 500 ){

}

You can make a small function to do the job and can use it like this:

pubic function isInRange($value, $min, $max){
return ($value <= $max && $value >= $min);
}

you can use this function like this:

$value = 16;

$ranges = array(
  'range1'=> array(
    'min'=> 1,
    'max'=> 10
  ),
  'range2'=> array(
    'min'=> 11,
    'max'=> 20
  )
);

  function isInRange($value, $min, $max){
  return ($value <= $max && $value >= $min);
}

foreach($ranges as $key => $range){
  echo (isInRange($value, $range['min'], $range['max']))? $key.' returned true': $key.' returned false';
}

An alternative option is to use the filter_var method:

filter_var(
$yourInteger, 
FILTER_VALIDATE_INT, 
array(
    'options' => array(
        'min_range' => $min, 
        'max_range' => $max
    )
)

);

Please, note that the filter_var method is type safe. You will see many good working examples at the bottom of the php.net site i linked above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM