TuK
TuK

Reputation: 3556

php improper comparison behavior

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

Upvotes: 1

Views: 65

Answers (2)

Mike Purcell
Mike Purcell

Reputation: 19999

Should be:

if (strlen($string) >= 34)) {

Not

if ($string >= 34)){

Upvotes: 2

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

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)){

Upvotes: 2

Related Questions