2010-01-15 4 views
0

내가 여기서 뭘 잘못하고 있니? 사용자 이름 문자열은 2 자 미만이지만 여전히 오류 []를 설정하지 않습니까?배열의 도움

등록 : 귀하의 기능이 errors라는 이름의 지역 변수, 당신이 예상되었을 수없는 글로벌 errors에 영향을 미치는 validate_username($username);

$errors = validate_username($username);

$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 = "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

다음과 같이

또한, 코드는 조금 정리 될 수있다. 당신이 올바른 방법을 반환하지 않을

$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; 
} 
를 할당하는 것을 잊었다