Alegro
Alegro

Reputation: 7956

Range condition with string length

I currently have this code:

if (strlen(trim($username) < 4)) {
$error='Username should be between 4 and 10 characters.';
}

if (strlen(trim($username) > 10)) {
$error='Username should be between 4 and 10 characters.';
}

I wish to reduce that into a simpler statement, like this (but that obviously doesn't work):

if (strlen(trim($username) < 4 >10))... // parse error

Upvotes: 1

Views: 4120

Answers (4)

vvolkov
vvolkov

Reputation: 1212

This syntax is incorrect, you should use || operator:

if (strlen(trim($username)) < 4 || strlen(trim($username)) > 10) {
    $error='Username should be between 4 and 10 characters.';
}

Upvotes: 3

MrCode
MrCode

Reputation: 64526

You're essentially just checking if a number is within a specified range, so another option would be filter_var(), although a little scary:

if(!filter_var(strlen(trim($username)), FILTER_VALIDATE_INT, array('options' => array('min_range' => 4, 'max_range' => 10))))
{
    $error='Username should be between 4 and 10 characters.';
}

Upvotes: 3

phpisuber01
phpisuber01

Reputation: 7715

Here you go, use of the || (or) operator will help.

Also take note how I assigned the username to variables to prevent the use of your trim() and strlen() functions being called multiple times. That's just wasteful.

Code

$username = trim('bob');
$username_length = strlen($username);
if ($username_length < 4 || $username_length > 10)
{
    echo 'Username should be between 4 and 10 characters.';
}

Upvotes: 2

Madbreaks
Madbreaks

Reputation: 19539

Well you could do:

(strlen(trim($username)) < 4 || strlen(trim($username)) > 10) && $error='Username should be between 4 and 10 characters.';

But it'd be a lot more efficient to define the trimmed username length first:

$len = strlen(trim($usename));
($len < 4 || $len > 10) && $error = "Bad username";

Upvotes: -1

Related Questions