开发者

Make an if statement shorter

Hay all, I have an if statement. How could I make this as short as possible?

 if ( $a < 0 ){
   if( $a > -2 ){
    echo "standard";
   }elseif( $a <= -2 && $a > -4 )开发者_JAVA百科{
    echo "thin";
   }elseif( $a <= -4 ){
    echo "super thin";
   }

 }else{
  if( $a < 2 ){
    echo "standard";
  }
  if( $a > 2.01 && $a <= 4){
    echo "thin";
  }
  if( $a > 4.01 && $a <= 8.00){
    echo "super thin";
  }
}

EDIT: basically $a will be any number (positive or negative) and we match it like this.

If the value is

  • +0.00 to +/- 2.00 – Standard
  • +/- 2.25 to +/- 4.00 – Thin
  • +/- 4.25 to +/- 8.00 – Super Thin

Extra marks for anyone who knows what this might be used for :)


You can shorten it by using the absolute value:

$b = abs($a);
if ($b <= 2) {
    echo "standard";
} else if ($b <= 4) {
    echo "thin";
} else if ($b <= 8) {
    echo "super thin";
}


What about this:

 $a = abs($a);
 if($a<=2) echo "standard";
 elseif($a<=4) echo "thin";
 elseif($a<=8) echo "super thin";


This is about as simple as it gets:

<?php
$b = abs($a);
$ranges = array(
  'standard' => 2,
  'thin' => 4,
  'super thin' => 8
);
foreach($ranges as $range=>$max) {
    $size = $range;
    if($b > $max) continue;
    break;
}
?>


Or you can keep the actual ranges, allow the range ends to be different (rather than just the absolute values), and allow easy inclusion of additional ranges:

$ranges = array(
  'standard' => array(-2, 2),
  'thin' => array(-4, 4),
  'super thin' => array(null,8),
);
foreach($ranges as $key => $range) {
  if((is_null($range[0]) || $a => $range[0]) && (is_null($range[1]) || $a <= $range[1])) {
    echo $key;
    break;
  }
}

The first matching range in the list is the one that qualifies.


if ( $a < 0 )
{
    if( $a > -2 ) echo "standard";
    elseif($a > -4) echo "thin";
    else echo  "super thin";
}
else
{
  if( $a < 2 ) echo "standard";
  elseif( $a > 2.01 && $a <= 4) echo "thin";
  elseif( $a > 4.01 && $a <= 8.00) echo "super thin";
}


Its always better to use switch rather than else if! It makes the code cleaner and extensible.

switch($a) {
    case (-2 < $a):
    case ($a < 2):
        $r = 'Standard';
    break;

    case ( 2.25 > $a):
    case (-2.25 < $a):
    case ($a <  4):
    case ($a > -4):
        $r = 'Thin';
    break;


    case ( 4.25 > $a):
    case (-4.25 < $a):
    case ($a <  8):
    case ($a > -8):
        $r = 'Super Thin';
    break;

    default:
        $r = 'Out of range';
} 

echo $r;

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

Taken from the documentation at http://us3.php.net/manual/en/control-structures.switch.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜