Tutorial :Should I use nested if .. else statements for a series of less than comparisons in PHP


I need to do a series of comparisons with an integer in PHP, returning a different string depending on the result and I am wondering if an if..else block is the most elegant method. The code looks like:

if( $total < 10000 ) {    return 'string A';  } elseif( $total < 20000 ) {    return 'string B';  } elseif( $total < 30000 ) {    return 'string C';  } elseif( $total < 40000 ) {    return 'string D';  } elseif( $total < 50000 ) {    return 'string E';  }  

Which works, I just don't think it's very pretty. If I was doing equality checks then I would use a switch block.


You could use an array like this (assuming that $total is always positive):

$results = array('string A', 'string B', 'string C', 'string D', 'string E');  $index = floor($total / 10000);  if ($index < 5) return $results[$index];  


If you want to use a switch-case statement as suggested in one of the comments you will have to write it like this:

switch(true) {    case ($total < 10000): return 'string A';    case ($total < 20000): return 'string B';    case ($total < 30000): return 'string C';    case ($total < 40000): return 'string D';    case ($total < 50000): return 'string E';  }  

Each case will be evaluated as true|false, and as soon as you script hits what it is looking for true it will return the corresponding string.

It will probably not be more efficient than your original code, but it is easier to read...


You could use a switch statement like:

switch (round($total / 10000)) {      case 0: //0xxxx          break;      case 1: //1xxxx          break;      case 2: //2xxxx          break;      case 3: //3xxxx          break;      ...  }  

I'm not a PHP programmer so syntax may be wrong.


You could also have a look at the Chain of Responsibility Pattern, though this could be somewhat overengieered for your UseCase.


This wouldn't work in cases where you are not returning based on the result, or when you need to do more than one operation, but with the example you provided, you wouldn't even need the else if's or a switch, it could just be:

if ($total < 10000) return 'A';  if ($total < 20000) return 'B';  if ($total < 30000) return 'C';  if ($total < 40000) return 'D';  if ($total < 50000) return 'E';  


From the code-reusing pov, op's style is quite satisfactory. It's easy to comprehend and modify. But, yeah, for "elegance", Gumbo's snippet is the way to go.

    if ($total < 10000) { return 'string A'; }   elseif ($total < 20000) { return 'string B'; }   elseif ($total < 30000) { return 'string C'; }   elseif ($total < 40000) { return 'string D'; }   elseif ($total < 50000) { return 'string E'; }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »