If you want to populate the $_SESSION['flash']['error']
with the error messages for the values that are not set, you can do it with a loop. Here I would create an array of all the required keys, then looping over those keys, check if the value is empty (in this example with $_POST
) and then insert the error message into the array -
// array of required keys
$required = ['firstname','lastname','age'];
// loop over the required keys
foreach($required as $key){
// check if that key value is empty
if(empty($_POST[$key])){
// if the value was empty, insert the corresponding error message into the array
$_SESSION['flash']['error'][] = $errors[$key];
}
}
but, if you simply just want to add all the error messages, without any conditionals, a simple loop would do this -
foreach($errors as $error) {
$_SESSION['flash']['error'][] = $error;
}
As an alternative, you could just loop over the $error
array. This has the same result as the 1st example, with the cleanness of the 2nd example. Here we check the $errors
keys, and then add the $errors
values.
foreach($errors as $key => $value) {
if(empty($_POST[$key])){
$_SESSION['flash']['error'][] = $value;
}
}