php - help with array -
what doing wrong here? username string less 2 chars 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 $cur_error) $errors[] = '<li class="warn"><span>'.$cur_error.'</span></li>'; } function validate_username($username) { $errors = array(); if (strlen($username) < 2) $errors[] = "username short"; else if (strlen($username) > 25) $errors[] = "username long"; return $errors;
}
change validate_username($username);
$errors = validate_username($username);
your function affecting local variable named errors
, not global errors
may have been expecting.
further, code can cleaned little bit follows
$username = "l"; $errors = validate_username($username); // no errors if ( empty($errors) ) { echo "nothing wrong here, inserting..."; } // errors present else { foreach ( $errors $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 short"; } elseif ( $len > 25 ) { $errors[] = "username long"; } return $errors; }
Comments
Post a Comment