简体   繁体   中英

php strlen function and 2 vars

if (strlen($title) > 2 && ($msg) > 2 && ($email) > 2)) {
 //true
} else {
 //false
}

What would be the correct way of checking more than 1 var? This wont work..tried many ways

What you have to note is that everything between a boolean operator (eg: &&) is not related to the other.

eg: strlen($a) && $b

is not the same as:

strlen($a) && strlen($b)

Unlike spoken language where you can say "a and b are larger then 2" you have to program it as "a is larger then 2 and b is larger then 2"

ie:

if (strlen($title) > 2 && strlen($msg) > 2 && strlen($email) > 2)

If you want a reusable function that checks lengths, and takes an arbitrary number of arguments something like this would work:

function validateLength() {

// get all passed in arguments
$args = func_get_args();
// get the first argument as the length
$len = array_shift($args);

foreach($args as $arg) {

  if (strlen($arg) < $len) return false;

}
return true;

}

Usage:

$valid = validateLength(2, $title, $msg, $email);

You just need to call strlen on the other two variables to test the length of test is > 2. Also, the last parenthesis should be removed. Like so:

if (strlen($title) > 2 && strlen($msg) > 2 && strlen($email) > 2) {

What about calling strlen for each one of the vars ?

if (strlen($title) > 2 && strlen($msg) > 2 && strlen($email) > 2) {
 //true
} else {
 //false
}

If you want to get the length of each variable, you should use the function that does this... on each one of those variables.

EDIT : should test the code before posting it : there is one closing parenthese in your code that doesn't belong ;-)

If you keep it, you'll get a Parse error.

I think you want to do this:

if (strlen($title) > 2 && strlen($msg) > 2 && strlen($email) > 2) {
  //true
} else {
 //false
}

When calling a function you need to specify the function name and then the arguments to that function in parenthesis immediately following the function name. If the function you want to use does not accept a variable number of arguments (like strlen for instance) you must call the function multiple times, once for each variable you have.

In cases like this it can often be best to encapsulate this kind of stuff in its own function like this:

function isValid($title, $msg, $email) {
    return 
        strlen($title) > 2 && 
        strlen($msg) > 2 && 
        strlen($email) > 2;
}

Then you would change your if statement to use the new function like this:

if (isValid($title, $msg, $email)) {
  //true
} else {
 //false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM