2010-03-07 85 views
3

任何想法爲什麼這不會打印錯誤?數組和foreach

// 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>'; 
} 
+0

能否請您與您的縮進少粗心?它會讓任何代碼維護者可能會恨你。我知道我正在冒... – brianreavis

回答

6

您在輸出之前覆蓋數組。

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

刪除$errors = array()它應該工作。

這將是在腳本的最開始初始化$errors = array()的方式清潔,然後檢查count($errors) > 0而不是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>'; 
} 

這樣一來,你會避免對$error沒有被設置的通知。

+0

爲什麼不'空着'?它爲空數組返回'true'。 –

+0

@Felix你是對的,我沒有想到這一點。 「空」也會起作用。 –

1

因爲該行溼巾數組:

$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

因爲如果最後的if語句覆蓋了第一行中的值$errors

3

...因爲你排空陣列只是想顯示其內容之前,請參見下面

// 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>'; 
}