简体   繁体   中英

PHP - problem with mb_strlen

I'd like to push a "value" into an "array" iff the string lenght is greater than 30. So I have done this PHP script :

if(!mb_strlen($string, 'utf-8')<=30) array_push($array, "value");

But It push that value also if the string is lesser than 31... why?

The reason it is doing that is the order in which PHP is processing your operators.

It processes !mb_strlen($string, 'utf-8') first, so if the length is non-zero that will return true.

It then evaluates true <= 30 , which is always true...

So essentially the only case your statement will be false is if a zero length string is given...

See the other answers for how you should write the statement.

Why don't you write the code as you verbalized it?

mb_strlen($string, 'utf-8') > 30

The reason why your condition fails is because ! has a higher operator precedence than <= . So !mb_strlen($string, 'utf-8') is evaluated before it is compared to 30 , ie:

(!mb_strlen($string, 'utf-8')) <= 30

And since any number except 0 evaluates to true when converted to boolean , the expression !mb_strlen($string, 'utf-8') is only true for an empty string. And as <= requires the first operand to be numeric, the boolean result of !mb_strlen($string, 'utf-8') is converted to integer where (int)true === 1 and (int)false === 0 and both is alway less than or equal to 30.

如果有条件,为什么不使用更简单的方法?

if (mb_strlen($string, 'utf-8') > 30) array_push($array, "value");

Your doing the operators wrong <= 30 which is less or equal to 30, thats whay all less then 31 are being passed, you should use.

to correct your mistake you should use > operator to show that the the left argument should be greater than the right argumen.

if you look closely at the design of the char you will see that the left side of the > is opened grater then the right side. (vice / versa)

The following links will describe the differences:

you will also notice that you have an exclamation mark in your if statement which causes php to transform the result into a bool before the length check is actually fired.

therefore you will always be try and evaulate true <= 30 , you should remove the exclamation mark.

Try rewrite you code like so:

if(mb_strlen($string, 'utf-8') > 30)
{
     array_push($array, "value")
}

您需要将测试括在方括号中:

if(!(mb_strlen($string, 'utf-8')<=30)) array_push($array, "value");

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