1

I'm trying to display a correct results based on the value of the variable but I'm using a short hand,

I have tried the following but its seems to ignore the first check even if the value is correct.

(!empty($national_ID_number)) ? 
    $national_ID_number : 
    (!empty($foreign_ID_number)) ?
        $foreign_ID_number  : 
        $temporal_permit_number)

Thanks

Ikari
  • 3,176
  • 3
  • 29
  • 34
Terabyte
  • 455
  • 2
  • 12
  • Could you possibly post the var dump of all the variables used? – Ikari Sep 07 '16 at 09:04
  • 6
    Short-hand if / else syntax is not obvious when using multiple conditions. They don't simply go left to right as you would expect. In this case, I'd recommend using standard if / else conditions. Otherwise, you need to use brackets to force the precedence of each condition to what you expect it to be. – Jonnix Sep 07 '16 at 09:05
  • Good lord. Don't write code like this--it makes your fellow humans' eyes bleed. Break it out to two nested if()s. The ternary operator is good for one item per segment only max (not technically, but as a practical matter). – BJ Black Sep 07 '16 at 09:08
  • If you need to do more than a simple `if / else` with ternary then I strongly suggest that you swap over to using proper if / else structure as the ternary operator very quickly becomes hard to read / understand. (And readability is just as important (if not more) as "compact" code is). – Epodax Sep 07 '16 at 09:08

2 Answers2

2

It's populating correctly for me with this code, you seem to have added additional bracket.

$national_ID_number = '';
$foreign_ID_number = 2;
$temporal_permit_number = 3;
$finalID = (!empty($national_ID_number)) ? $national_ID_number : (!empty($foreign_ID_number ) ? $foreign_ID_number  : $temporal_permit_number);
echo $finalID;
SanketR
  • 1,182
  • 14
  • 35
0

I just went for a bit deep research - apparently each condition needs to be inside brackets and the below fix works fine.

(!empty($national_ID_number)) ? 
    $national_ID_number : 
    ((!empty($foreign_ID_number)) ?
        $foreign_ID_number  : 
        $temporal_permit_number));

Reference and PHP Operator precedence

Community
  • 1
  • 1
Terabyte
  • 455
  • 2
  • 12