PHP 中的空格验证与 for 循环


empty space validation in PHP with a for loop

如您所见,我有一个简单的注册表和一个PHP脚本,仅用于验证某些字段。这里的想法是,如果您有 20+ 字段,并且您至少需要用户填写......用户名,姓氏和年龄,然后您将它存储在一个数组中,就像我在下面所做的那样。

$needed = array("username", "lastname", "age"); 因此,正如您在代码中看到的那样,我做了一个for循环来检查其中一个是否已填充,现在代码大部分都有效。 例如:如果你不填写这三个字段,它会说

您必须填写用户名才能继续

您必须填写姓氏才能继续

您必须填写年龄才能继续

但是,如果您填写字段并留下其他两个,或者填写两个然后留下一个,它只会回显'<p>Required fileds are filled</p>';

所以,这里的问题是,在脚本可以说echo '<p>Required fileds are filled</p>';之前,应该填写所有字段

<pre>
<form action='' method='POST'>
    <input type='text' name='username' />
    <input type='text' name='lastname' />
    <input type='text' name='age' />
    <input type='text' name='gender' />
    <input type='text' name='country' />
    <input type='submit' name='reqirester' />
</form>

<?php 
    $needed = array("username", "lastname", "age");
  if($_POST):
    $check = NULL;
for($i=0; $i < count($needed); $i++){
        if($_POST[$needed[$i]] == ''){
          echo '<p>You must fill '.$needed[$i].' to continue<p/>';
        break;  
        }else {
            echo '<p>Required fileds are filled</p>';
        }
    }
 endif;

为什么不:

$required = array("username", "lastname", "age");
$missing = array_keys(array_diff_key(array_flip($required), array_filter($_POST)));
if($missing)
  printf('You missed: %s', implode(', ', $missing));

或使用您的输出:

foreach($missing as $key)
  printf('<p>You must fill %s to continue</p>', $key);
if(!$missing)
  print '<p>Required fileds are filled</p>';
$needed = array("username", "lastname", "age");
$error = false;
$msg = '';
foreach ($needed as $value) {
    if(empty($_POST[$value]) {
      $msg =. 'please fill in ' . htmlspecialchars($_POST[$value]) .'<br/>';
      $error = true;
    }
}
if($error === true) {
  echo $msg;
} else {
  echo 'Great! finished';
}