tony
tony

Reputation: 1

Returned value from non-native function is not accessible in global scope

What am I doing wrong here? The username string is less than 2 chars, but it still doesn't set error[]?

$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;
}

Upvotes: -1

Views: 98

Answers (5)

John
John

Reputation: 1

**//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;
}

Upvotes: 0

Silvio Donnini
Silvio Donnini

Reputation: 3303

you forgot to assign $errors

  $errors = validate_username($username);

Upvotes: 0

Malfist
Malfist

Reputation: 31795

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

$errors = validate_username($username)

Upvotes: 0

Pekka
Pekka

Reputation: 449395

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

Try

 $errors = validate_username($username);

Upvotes: 2

Justin Johnson
Justin Johnson

Reputation: 31300

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;
}

Upvotes: 1

Related Questions