Reputation: 48045
I'd like to push a "value" into an "array" if the string length 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?
Upvotes: -1
Views: 1638
Reputation: 57278
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")
}
Upvotes: 1
Reputation: 655815
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
, i.e.:
(!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.
Upvotes: 4
Reputation: 4648
You need to enclose the test in brackets:
if(!(mb_strlen($string, 'utf-8')<=30)) array_push($array, "value");
Upvotes: 1
Reputation: 8344
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.
Upvotes: 7
Reputation: 1930
Why don't you use more simple if condition?
if (mb_strlen($string, 'utf-8') > 30) array_push($array, "value");
Upvotes: 1