帮助数组

时间:2010-01-15 20:40:52

标签: php arrays

我在这里做错了什么?用户名字符串少于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;

}

5 个答案:

答案 0 :(得分:2)

这是因为您没有将validate_username()的返回值分配给任何变量。

尝试

 $errors = validate_username($username);

答案 1 :(得分: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 :(得分:0)

你没有以正确的方式回归,你需要:

$errors = validate_username($username)

答案 3 :(得分:0)

您忘了分配$errors

  $errors = validate_username($username);

答案 4 :(得分: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;
}