Lei Lionel Lei Lionel - 5 months ago 14x
PHP Question

Add values to an unknown number of elements in an array

I am making a project in PHP and I created multiple variables as following:

$errors = array();
$errors['firstname'] = 'Enter First Name'
$errors['lastname'] = 'Enter Last Name'
$errors['age'] = 'Enter Age'

And I am having an other array
to display the errors in the projects.

What I want, it is to get an array like this:
$_SESSION['flash']['error'] = ('Enter First Name', 'Enter Last Name', 'Enter Age')

Kindly help me solve this problem. Thanks in advance.


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 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) {
        $_SESSION['flash']['error'][] = $value;