2010-01-15 100 views
0

我在這裏做錯了什麼?用戶名字符串小於2個字符,但它仍然不設置錯誤[]?幫助陣列

註冊:

$errors = array(); 

$username = "l"; 

    validate_username($username); 

if (empty($errors)) { 
    echo "nothing wrong here, inserting..."; 
} 

if (!empty($errors)) { 

    foreach ($errors as $cur_error) 
     $errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>'; 
} 


function validate_username($username) { 

$errors = array(); 

if (strlen($username) < 2) 
    $errors[] = "Username too short"; 
else if (strlen($username) > 25) 
    $errors[] = "Username too long"; 

return $errors; 

}

回答

1

變化validate_username($username);$errors = validate_username($username);

你的功能影響名爲errors一個局部變量,而不是全球errors,你可能已經預期。

此外,如下

$username = "l"; 
$errors = validate_username($username); 

// No errors 
if (empty($errors)) { 
    echo "nothing wrong here, inserting..."; 
} 
// Errors are present 
else { 
    foreach ($errors as $cur_error) { 
     $errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>'; 
    } 
} 

function validate_username($username) { 
    $errors = array(); 
    $len = strlen($username); 

    if ($len < 2) { 
     $errors[] = "Username too short"; 
    } elseif ($len > 25) { 
     $errors[] = "Username too long"; 
    } 

    return $errors; 
} 
2

那是因爲你沒有指定的validate_username()任何變量的返回值的代碼可以被清理一點點。

嘗試

$errors = validate_username($username); 
0

你沒有返回正確的方式,你需要:

$errors = validate_username($username) 
0

你忘了分配$errors

$errors = validate_username($username); 
0
**//TRY THIS INSTEAD** 

$errors = array(); 

$username = "l"; 

**$errors = validate_username($username);** 

if (empty($errors)) { 
    echo "nothing wrong here, inserting..."; 
} 

if (!empty($errors)) { 

    foreach ($errors as $cur_error) 
     $errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>'; 
} 


function validate_username($username) { 

$errors = array(); 

if (strlen($username) < 2) 
    $errors[] = "Username too short"; 
else if (strlen($username) > 25) 
    $errors[] = "Username too long"; 

return $errors; 
}