Iggy's Pop
Iggy's Pop

Reputation: 599

how to store form validation errors in an array

If I have some basic form validations, (just using empty() for simplicities sake) and want to put those error messages into an array, how would I achieve this?

 $errors = array();
 $response = array();

if(empty($_POST['name'])) {

    $errors['name'] = "Name required";
}

if(empty($_POST['email'])) {

    $errors['email'] = "Email required";
}

$response['errors'] = $errors;

if(!empty($errors)) {

    $response['success'] = false;
    $response['message'] = "fail";

} else {

    $response['success'] = true;
    $response['message'] = "<div class='alert alert-success'>Success</div>";
}

echo json_encode($response);
}

Upvotes: 0

Views: 690

Answers (1)

user10089632
user10089632

Reputation: 5560

    $message = [];

if(empty($_POST['name'])) {

array_push($message , "Name required <br />");

}

if(empty($_POST['email'])) {

array_push($message , "Email required <br />");

}

if(!empty($message)) {
foreach ( $message as $str)
echo "<div class='alert alert-danger'>" . $str . "</div>";

} else {
// success 

}

Upvotes: 1

Related Questions