I'm want to shorten the following if statement:
function is_string_length_correct( $string, $min, $max = 0 ) {
if (is_string($string)) {
$l = mb_strlen($string);
if ($max != 0) {
return ($l >= $min && $l <= $max);
} else {
return ($l >= $min);
}
}
}
Can someone explain me why the followin shorthand if doesn't work?
function is_string_length_correct( $string, $min, $max = 0 ) {
if (is_string($string)) {
$l = mb_strlen($string);
return ($max != 0) ? ($l >= $min && $l <= $max) : ($l >= $min);
}
}
Thank you
The syntax is fine. The problem likely lies with the value of $max
at runtime. 0
is falsy, so you are comparing it to the integer zero, it should be ($max !== 0)
.
您也可以只使用布尔运算符来编写它:
return $l >= $min && ($l <= $max || $max == 0);
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.