dormbaf90464
2018-06-14 22:07
浏览 270
已采纳

如何在PHP中使用if语句中的变量

I am trying to take a value inside of if/else statement and send an error message with "that variable" because I don't want any of my inputs to be more than 99 characters.

This is the code:

if(empty($x) || empty($y) || empty($z)){

$_SESSION["ErrorMessage"]="You have to fill all the blanks.";
redirect_to("addxyz.php");


} elseif(strlen($x)>99 || strlen($y)>99 || strlen($z)>99){

$_SESSION["ErrorMessage"]="Very Long  Name for /*variable name will be here*/";
redirect_to("addxyz.php");

}  else {/*Rest of the code*/}

In the second part when I use strlen function with variables, I need to select one of it with an array or any other way but not using 3 different if/else statement. What would be the best way ?

Thanks in advance.

图片转代码服务由CSDN问答提供 功能建议

我试图在if / else语句中取一个值并发送带有“that variable”的错误消息,因为 我不希望我的任何输入超过99个字符。

这是代码:

  if(empty($ x)|| empty($ y)|| empty($ z  )){
 
 $ _SESSION [“ErrorMessage”] =“你必须填补所有空白。”; 
 
directirect_to(“addxyz.php”); 
 
 
} elseif(strlen($ x)  > 99 || strlen($ y)> 99 || strlen($ z)> 99){
 
 $ _SESSION [“ErrorMessage”] =“/ *变量名称的非常​​长名称将在这里*  /";
redirect_to("addxyz.php");

} else {/ *其余代码* /} 
   
 
 

在第二部分 当我使用带有变量的strlen函数时,我需要使用数组或任何其他方式选择其中一个但不使用3个不同的if / else语句。 什么是最好的方式?

提前致谢。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongqian9013 2018-06-14 22:18
    已采纳

    You could make an array with your three variables and then validate them with a foreach loop. Even in the same foreach loop you could make the first validation you have:

    foreach(array($x, $y, $z) as $values) {//---> the $values variable represents each of your '$x, $y, $z' variables in the loop.
        if (empty($values)) {
            $_SESSION["ErrorMessage"]="You have to fill all the blanks.";
            redirect_to("addxyz.php");
    
        } else if (strlen($values) > 99) {
            $_SESSION["ErrorMessage"]="Very Long  Name for $values";//---> This will notify the first value that fails the validation.
            redirect_to("addxyz.php");
        }
    }
    

    If more than one value fails the validation (for example $x and $z) and you want to notify them all, you could save the $values value in an array and then show it. Something like this:

    $strlenErrors = array();
    foreach(array($x, $y, $z) as $values) {
        if (strlen($values) > 99) {
            $strlenErrors[] = $values;
        }
    }
    
    if (!empty($strlenErrors)) {
        $_SESSION["ErrorMessage"]="Very Long  Name for: ".implode(", ", $strlenErrors);//---> This will divide and print the '$strlenErrors' array by commas.
        redirect_to("addxyz.php");
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报