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

如何在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.

  • 写回答

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");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝