2010-01-15 98 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; 
}