开发者

How can Interval be used differently in php

开发者 https://www.devze.com 2023-01-21 07:34 出处:网络
I need to solve a problem like below. I\'m not sure, can you suggest better method? switch(true){ 开发者_运维问答case $price>100:

I need to solve a problem like below. I'm not sure, can you suggest better method?

switch(true){
  开发者_运维问答  case $price>100:
        tooHigh(); 
    break;
    case (($price<=100) && ($price>70)):
        negotiate(); 
    break;
    case (($price<=70) && ($price>20)):
        accept(); 
    break;
    case ($price<=20):
        thankAndEscape(); 
    break;
}



if ($price <= 20) {
        thankAndEscape(); 
} elseif ($price <= 70) {
        accept();
} elseif ($price <= 100) {
        negotiate(); 
} else {
        tooHigh(); 
}
  1. switch(true) is necessary in a small number of cases; the fact you make the check with expressions inside the case keyword means the syntax does not fit at all, that's a good reason to use the if...elseif construct.
  2. switch...case syntax has higher performances in PHP than if...else in case there's not a default case, so given the solution I suggest (which has a default case) I would not use the switch...case syntax.
  3. By making progressive checks, starting from the lowest price range and increasing it step by step, you don't have to check for the whole range, since the first point of the interval is surely greater than the last of the previous check. The solution I suggest is simpler and solid, giving moreover better performances.

Try it and post the results/your impressions (information about performances are appreciated :)

Cheers!


if($price > 100)
{
  //too high
  tooHigh()
}
elseif($price > 70) //it wasn't greater than 100 - is it greater than 70?
{
  //negotiate
  negotiate()
}
elseif($price > 20) //OK, wasn't greater than 70 OR 100 - greater than 20 then?
{
  //accept
  accept()
}
else //Guess not - just don't do anything
{
  //thank and escape
  thankAndEscape()
}

Case statements can't do conditions unfortunately. They really are 'if this is the case then...' in brutal honesty

This should work as the conditions will simply fall through to the next until it reaches the bottom. if one matches - the rest of the statement is ignored... Thats if I have my logic the right way up...

I don't think you'll need to do the range matching as is already native to the if statement. For example. The statement 'between 70 and 20 ' is simplified to above 20 lower than 70 in seperated conditions. A little more efficient and easier to read.


if ($price>100)
{
        tooHigh(); 
}
elseif($price<=100) && ($price>70))
{
        negotiate(); 
}
elseif(($price<=70) && ($price>20))
{
        accept(); 
}
elseif ($price<=20)
{
        thankAndEscape(); 
}

looks more compact and readable, doesn'it?


Use do-while.

do {

if($price > 100) { tooHigh(); break; }

} while(false);

http://php.net/manual/de/control-structures.do.while.php

0

精彩评论

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