tags:

views:

42

answers:

5

What am i doing wrong here? The username string is less than 2 chars but it still dont set error[]?

Register:

$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  A: 

Change validate_username($username); to $errors = validate_username($username);

Your function is affecting a local variable named errors, not the global errors that you may have been expecting.

Further, your code can be cleaned up a little bit as follows

$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;
}
Justin Johnson
+2  A: 

It's because you are not assigning the return value of validate_username() to any variable.

Try

 $errors = validate_username($username);
Pekka
A: 

you're not returning it the right way, you need:

$errors = validate_username($username)
Malfist
A: 

you forgot to assign $errors

  $errors = validate_username($username);
Silvio Donnini
A: 
**//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;
}
John