help with array
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)) {
fore开发者_开发问答ach ($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;
}
It's because you are not assigning the return value of validate_username()
to any variable.
Try
$errors = validate_username($username);
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;
}
you're not returning it the right way, you need:
$errors = validate_username($username)
you forgot to assign $errors
$errors = validate_username($username);
**//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;
}
精彩评论