Question

I want to add 2 numbers in the strlen command. here is my php code:

$name = mysql_real_escape_string($_POST['dgt']);
if(strlen($name) != "32") {
print "This is not a name.";
} else {

It checks if the length is 32. I want it to check if the length is 32 OR 40. how can I do that?

Was it helpful?

Solution 3

From the PHP: Logical Operators - Manual, you want to use either

  1. or
  2. || (this form has higher precedence)
$a or $b    Or  TRUE if either $a or $b is TRUE.
$a || $b    Or  TRUE if either $a or $b is TRUE.

So, you could use something like this

$len = strlen($name);         // just get the length once and then 
                              // use it to compare however many times....
if (!($len == 32 or $len == 40))

OTHER TIPS

First of all, don't use mysql_real_escape_string(); the old mysql_ API is deprecated, so consider switching to PDO or mysqli instead.

Second, you should consider using input filtering; $_POST['dgt'] may not exist at all, so use filter_input().

Third, you should use numeric values to compare against the output of strlen(); although PHP will treat "32" as a number, it's better to be explicit.

Lastly, if a name must be either 32 or 40 long, you can simply add the condition:

$name = filter_input(INPUT_POST, 'dgt', FILTER_UNSAFE_RAW);
if (empty($name) || (strlen($name) != 32 && strlen($name) != 40)) {
    print "This is not a name.";
}

Alternatively, use in_array():

if (empty($name) || !in_array(strlen($name), array(32, 40))) {
    print "This is not a name.";
}

Use the and operator "&&" in your conditional, like the code below.

if(strlen($name) != 32 && strlen($name) != 40)

If you would like it to check if name is length 32 or 40 then use the or operator "||" like the code below.

if(strlen($name) == 32 || strlen($name) == 40)

user2910265 has a good point, assign the return value of strlen() to a variable so that only one call is made, like so.

$length = strlen($name);
if(!($length == 32 || $length == 40))
    print "this is not a name.";
} else {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top