0

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.

Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
vijay kani
  • 140
  • 8
  • Well it will always return 30, you got `<=` condition doubled. Try this `(5 >= $len) && ($len <= 6)` and `(7 >= $len) && ($len <= 8)` – AmBeam Jul 09 '15 at 09:22
  • Each expression must be contained in parenthesis. – Inurosen Jul 09 '15 at 09:22
  • 1
    If you would read the php documentation and other literature (on-/offline) you would have noticed that complex ternary operations are strongly discouraged... Not just because of readability, but also because it's very error-prone. If you need to compare more than one, use regular conditions (if-else)... – Raphioly-San Jul 09 '15 at 09:24
  • possible duplicate of [Using nested ternary operators](http://stackoverflow.com/questions/8735280/using-nested-ternary-operators) – OIS Jul 09 '15 at 09:36

2 Answers2

1

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
ash__939
  • 1,614
  • 2
  • 12
  • 21
1

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

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87