Arun Killu
Arun Killu

Reputation: 14233

evaluation of ternary operator in php

echo strlen('Hello World') > 2 ? '...' : '' . substr('Hello World',0,2);

above code output:

...

what I except was

...He

Can anyone explain how the above code is evaluated in php

EDIT

echo substr('Hello World',0,2) . strlen('Hello World') > 2 ? '...' : '';

OUTPUT

NO OUTPUT

BUT this works

echo substr('Hello World',0,2), strlen('Hello World') > 2 ? '...' : '';

OUTPUT

He...

Upvotes: 1

Views: 532

Answers (2)

awm
awm

Reputation: 6570

It's evaluated like this:

echo strlen('Hello World') > 2 ? '...' : ('' . substr('Hello World',0,2));

What you probably want is this:

echo (strlen('Hello World') > 2 ? '...' : '') . substr('Hello World',0,2);

Upvotes: 5

Realitätsverlust
Realitätsverlust

Reputation: 3953

The same as if-condition:

if(strlen('Hello World') > 2) {
    echo '...';
} else {
    echo '' . substr('Hello World',0,2);
}

Upvotes: 1

Related Questions