简体   繁体   中英

STRLEN in PHP something's wrong

just a quick question regarding STRLEN in php... below is my code where I believe somewhere is wrong but just don't know where..

what im trying to do (obviously) is to show error message if there is less than 2 (excluding 2) characters in each of the text boxes..

WHen i run this, it's doing absolutely nothing so there must be something wrong with it.

Any help definitely appreciated!!

 $error_message = "";
        if(strlen($username) < 2) {
        $error_message .= 'The username you entered do not appear to be valid.<br />';
      }
        if(strlen($start) < 2) {
        $error_message .= 'The start time you entered do not appear to be valid.<br />';
      }
        if(strlen($end) < 2) {
        $error_message .= 'The end time you entered do not appear to be valid.<br />';
      }
        if(strlen($location) < 2) {
        $error_message .= 'The location you entered do not appear to be valid.<br />';
      }
        if(strlen($department) < 2) {
        $error_message .= 'The department you entered do not appear to be valid.<br />';
      }
      if(strlen($error_message) > 0) {
        died($error_message);
      }

2 or less means you need to do:

if(strlen($variable) <= 2)

What you are doing is less than 2 which excludes 2 (1 or less)

Did you check what value you are getting in strlen($username),strlen($department),... What is the error you are getting ?

New Edit

Try to add else ,this will make you sure that code is readed .

 if(strlen($username) < 2) {echo "The username you entered do not appear to be valid.<br />";}
else {echo "username is present";}

best approach is to use something like

if(isset($username{3}) ... ) {
    ....
  }
...

there is simple reason to use $var_name{IndexOf} because its faster then strlen and indirectly it is also checking weather its greater then 2

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