php multiple if conditions

前端 未结 5 1940
既然无缘
既然无缘 2021-01-29 11:16

when i try to filter all these parameters php only enters in the first if conditions, ignoring all others conditions.

if($t_red<0){
    $t_red=0;
}

else if($         


        
相关标签:
5条回答
  • 2021-01-29 11:48

    a successfully met condition of an if (or following else if) statement will ignore all else if/else statements that immediately follow it, but the if statements afterwards are executing - You can verify this by adding echo statement to each one . Could it perhaps be because all your variable assignments are for $t_red so no action is taken on $t_green or $t_blue?

    0 讨论(0)
  • 2021-01-29 11:49
    if($t_red < 0)
    {
        $t_red = 0;
    }
    else if($t_red > 255) //Original won't catch it if it is == to 256, have to do either >= 256 or > 255
    {
        $t_red = 255;
    }
    
    if($t_green < 0)
    {
        $t_green = 0;
    }
    else if($t_green > 255)
    {
        $t_green = 255;
    }
    
    if($t_blue < 0)
    {
        $t_blue = 0;
    }
    else if($t_blue > 255)
    {
        $t_blue = 255;
    }
    

    Andrew Sledge's answer is the best though, but I did correct the fact that it would miss correcting the value if it was == to 256, which wouldn't be caught by just $var > 256, and thus would be in error if the value has to be between 0 and 255.

    0 讨论(0)
  • 2021-01-29 11:52

    Probably best suited if ran through a filtering function.

    function setParam($param) {
      if($param < 0) {
        $param = 0;
      } elseif($param > 256) {
        $param = 255;
      }
    
      return $param;
    }
    
    $t_green = setParam($t_green);
    $t_red = setParam($t_red);
    $t_blue = setParam($t_blue);
    

    You could also use pass-by-reference if necessary.

    0 讨论(0)
  • 2021-01-29 12:06
    $t_red=$t_red<0?0;$t_red;
    $t_red=$t_red>=256?255;$t_red;
    
    
    //are you sure you're modifying t_red here? and not t_green?
    $t_red=$t_green<0?0;$t_red;
    $t_red=$t_green>=256?255;$t_red;
    
    //are you sure you're modifying t_red here? and not t_blue?
    $t_red=$t_blue<0?0;$t_red;
    $t_red=$t_blue>=256?255;$t_red;
    
    0 讨论(0)
  • 2021-01-29 12:13

    It's not clear what you're trying to do, but I think that you would want to remove the else before the third if statement and add an else before the sixth if statement.

    0 讨论(0)
提交回复
热议问题