PHP strlen question

2019-02-26 09:08发布

Ok I am checking that a string is at least 4 characters long and 25 or less characters short

I tried to use strlen like this

$userNameSignupLength = strlen($userNameSignup);

else if($userNameSignupLength<4 && $userNameSignupLength>25) {

            $userNameSignupError = "Must be between 4 to 25 characters long";

        }

but it doesn't work... what did I do wrong?

5条回答
冷血范
2楼-- · 2019-02-26 09:50

Using strlen is correct to check the length of a string (in bytes). But a number cannot be both smaller than 4 and greater than 25 at the same time. Use || instead:

if ($userNameSignupLength < 4 || $userNameSignupLength > 25)

Now the condition is fulfilled if the number is either smaller than 4 or greater than 25.

查看更多
戒情不戒烟
3楼-- · 2019-02-26 09:52

and get rid of the 'else' in front of the 'if' keyword!

查看更多
甜甜的少女心
4楼-- · 2019-02-26 09:54

I think you want an OR there:

else if($userNameSignupLength < 4 || $userNameSignupLength > 25) {

Like Gumbo said, the length cannot possibly be both less than 4 AND greater than 25. && means and.

查看更多
Juvenile、少年°
5楼-- · 2019-02-26 10:06

Change the && to ||

else if ($userNameSignupLength<4 || $userNameSignupLength>25)
查看更多
贪生不怕死
6楼-- · 2019-02-26 10:07

With your code, it is evident that you are trying to validate a text field. You have not shared html of this code. Anyways , from my expertise i will say that you should not use &&. You should use ||. Also you should not directly use else if. You should use if for this code.

查看更多
登录 后发表回答