phpfunctionreturn

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

Solution

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