php multiple if conditions

自古美人都是妖i 提交于 2019-12-02 23:26:14

问题


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($t_red>256){
    $t_red=255;
}

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

else if($t_green>256){
    $t_red=255;
}

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

if($t_blue>256){
    $t_red=255;
}

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

回答1:


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.




回答2:


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.




回答3:


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



回答4:


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?




回答5:


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.



来源:https://stackoverflow.com/questions/4810424/php-multiple-if-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!