Search code examples
phparrays

Array is always empty even when it is expected to have elements


Any idea why this wont print the errors?

// Validate the email
if (preg_match($regex, $email))  
        $errors[] = "Invalid email address";

// ... and the password
if (strlen($password) < 4)
    $errors[] = "Password is too short";

// No errors?   
if (empty($errors))
{
    // insert into db
}

// If there were any errors, show them
if (!empty($errors))
{
    $errors = array();
    foreach ($errors as $error)
        echo '<li>' . $error . '</li>';
}

Solution

  • you are overwriting the array before output.

     $errors = array();  // Creates an empty array
     foreach ($errors as $error)  // Won't do anything
    

    remove $errors = array() and it should work.

    It would be cleaner by the way to initialize $errors = array() in the very beginning of the script, and then check for count($errors) > 0 instead of empty:

    // No errors?   
    if (count($errors) == 0)
    {
     // insert into db
    
    }
    
    // If there were any errors, show them
    else
    {
        $errors = array();
        foreach ($errors as $error)
        echo '<li>'.$error.'</li>';
    }
    

    that way, you will avoid notices about $error not being set.