Reputation: 1051
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
Upvotes: 0
Views: 115
Reputation: 265547
You can also write it only with boolean operators:
return $l >= $min && ($l <= $max || $max == 0);
Upvotes: 1
Reputation: 77996
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)
.
Upvotes: 3