php improper comparison behavior
-
27-02-2021 - |
Frage
$string = '540';
if (strlen ($string >= 34)){
print_r((substr($string, 0, 30) . "..."));
} else {
print_r(($string));
}
If $string
is longer than 34 characters it should be appended with a "...", otherwise it should just print the string.
I think what's happening is that the interpreter is assuming the string is a number when it does the comparison.
It also has the same hiccup if I change $string
to
$string = '540 rocks !'
Why is this?
Lösung
Should be:
if (strlen($string) >= 34)) {
Not
if ($string >= 34)){
Andere Tipps
If the test you want to do is on the string length, just change this line:
if ($string >= 34)){
into this:
if (strlen($string) >= 34)){
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow