vijay kani
vijay kani

Reputation: 140

Complex ternary operator

I have use this ternary operator. To check my length variable $len, based on that return values

My length is taken from

$len = strlen($indChar); // values up to 3 ... 8

when it pass the value of 3 it strangely returns 30

$lft = ($len <= 4) ? 10 : 
       ((5 <= $len) && ($len <= 6)) ? 20 : 
       ((7 <= $len) && ($len <= 8)) ? 30 : 35;

var_dump($lft); //30

I don't know what I did wrong. If anything wrong please correct me.

Upvotes: 0

Views: 199

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31739

Use () to specify the conditions separately. Try with -

$len = 3;
$lft = ($len <= 4) ? 10 : 
       (((5 <= $len) && ($len <= 6)) ? 20 : 
       (((7 <= $len) && ($len <= 8)) ? 30 : 35));
echo $lft; // 10

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

DOCS

Check it here

Upvotes: 1

ash__939
ash__939

Reputation: 1599

The problem is with using the conditions. Enclose each condition in separate brackets.

$len = 3
$lft = ($len <= 4) ? 10 : 
    (((5 <= $len) && ($len <= 6)) ? 20 : 
    (((7 <= $len) && ($len <= 8)) ? 30 : 35));
echo $lft; // 10

Upvotes: 1

Related Questions