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

报告相同问题?

悬赏问题

  • ¥65 LineageOs-21.0系统编译问题
  • ¥30 关于#c++#的问题,请各位专家解答!
  • ¥15 App的会员连续扣费
  • ¥15 不同数据类型的特征融合应该怎么做
  • ¥15 用proteus软件设计一个基于8086微处理器的简易温度计
  • ¥15 用联想小新14Pro
  • ¥15 multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)
  • ¥15 w3wp,exe 中发生未处理的 Microsoft ,NETFramework 异常。
  • ¥20 C51单片机程序及仿真(加减器)
  • ¥15 AQWA | 水动力分析 二阶波浪力