-2

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?

3 Answers3

4

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.";
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

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 {
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
  • On top of this, put strlen in a variable name so that it only gets called once (instead of twice). The interpreter will not likely be smart enough to do this for you. – user2910265 Dec 16 '13 at 04:18
  • Oh, I thought you were talking about the second conditional using or. The OP's question is confusing because he says his code is checking if the string is of length 32 when it is actually checking if it is not 32, so I got confused in answering. – Jonny Henly Dec 16 '13 at 04:44
0

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))
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249