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?
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.