Reputation: 334
The following code cycles through an array of requirements for user submitted data (in this case from a registration form) and outputs repetitive error messages. How to stop the repetitive messages?
if(!empty($_POST)){
$validate = array(
'username' => array(
'required' => true,
'min' => 3,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_confirm' => array(
'required' => true,
'matches' => 'password'
)
);
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$errors[] = "{$item} is required <br>";
}
}
if(!empty($errors))
{
foreach($errors as $error)
{
echo $error;
}
}
else
{
echo 'Registration Successful <br>';
}
}}
Output:
username is required
username is required
password is required
username is required
password is required
password_confirm is required
Upvotes: 1
Views: 35
Reputation: 41820
Your loops have gotten a bit mixed up.
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$errors[] = "{$item} is required <br>";
}
}
}
// This piece that prints out the errors (if they are present) needs
// to be moved outside the loop that creates the error array.
if(!empty($errors))
{
foreach($errors as $error)
{
echo $error;
}
}
else
{
echo 'Registration Successful <br>';
}
Also, maybe you simplified this code for the purpose of asking the question, but if this is all there is to it, why not just print the error at the time you find it instead of appending it to an array of errors? That way you only have to loop once. You can just use a boolean to see if there were errors.
$has_errors = false;
foreach($validate as $item => $rules)
{
foreach($rules as $rule => $rule_value)
{
$value = $_POST[$item];
$item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);
if($rule === 'required' && empty($value))
{
$has_errors = true;
echo "{$item} is required <br>";
}
}
}
if (!$has_errors) echo 'Registration Successful <br>';
Upvotes: 2