Arrays and foreach

Any idea why this is not printing 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>';
}
+3
source share
5 answers

you rewrite the array before exiting.

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

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

It would be cleaner to initialize $errors = array()at the very beginning of the script, and then check count($errors) > 0instead 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>';
}

this way you will avoid notifications about $errorwhich will not be set.

+6
source

... because you are freeing the array before trying to display its contents, see below

// If there were any errors, show them
if (!empty($errors))
{
    $errors = array();              // This line is emptying the array!
    foreach ($errors as $error)
    echo '<li>'.$error.'</li>';
}
+3
source

:

$errors = array();
+1

:

if (!empty($errors))
{
    $errors = array();    // Here, you are making the $errors array empty !
    foreach ($errors as $error)
    echo '<li>'.$error.'</li>';
}

: , foreach - foreach , .

+1

$errors , if.

+1

Source: https://habr.com/ru/post/1735826/


All Articles