Bir if deyimi kısaltmak

5 Cevap php

Hay tüm, bir if deyimi var. Nasıl bu mümkün olduğunca kısa yapabilir?

 if ( $a < 0 ){
   if( $a > -2 ){
    echo "stveard";
   }elseif( $a <= -2 && $a > -4 ){
    echo "thin";
   }elseif( $a <= -4 ){
    echo "super thin";
   }

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

EDIT: temelde $a (pozitif veya negatif) herhangi bir sayı olabilir ve bu gibi maç olacak.

Eğer bu değer

  • 2.00 - - +0.00 + / Stveart
  • + / - 2.25 + / - 4.00 - İnce
  • + / - 4.25 + / - 8.00 - Süper İnce

Bunun için kullanılan olabilir ne bilen herkes için ekstra işvardırtleri :)

5 Cevap

Sen mutlak değeri kullanarak kısaltabilir:

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

Ne bu konuda:

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

Bu alır gibi yaklaşık olarak basittir:

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

Yoksa, gerçek aralıkları tutmak aralığı (yerine sadece mutlak değerlerde daha) farklı olmak biter izin ve ek aralıkları kolay dahil izin verebilir:

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

Listedeki ilk eşleşme aralığı nitelendirir biridir.

Onun her zaman daha iyi kullanmak switch ziyade else if! Bu kod temiz ve genişletilebilir yapar.

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.

http://us3.php.net/manual/en/control-structures.switch.php de belgelerine alınan