0

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);
}
5
  • 2
    Just use an array instead of a string: message[] = "..." Commented Jul 4, 2017 at 16:59
  • I see you're using bootstrap. Are you using a PHP framework? Commented Jul 4, 2017 at 17:10
  • Yes, I am using bootstrap Commented Jul 4, 2017 at 17:11
  • 1
    Just like Marvin said, use $message[] or $message = array(). then just iterate. Commented Jul 4, 2017 at 17:13
  • I actually need to update my code because I want to use json. But I still need to get the errors into an array. Please see new code Commented Jul 4, 2017 at 17:19

1 Answer 1

1
    $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 

}
Sign up to request clarification or add additional context in comments.

1 Comment

Apologies, I changed the code in the initial question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.