0

I have custom ternary operation where I get user gender from numbers:

Code:

$value = 0;
$gender = $value === 0 ? 'Male' : $value === 1 ? 'Female' : 'Other';
echo $gender;

In my think this code must return Male but return Female. Here is example.

Or my ternary operation incorrect for getting Male result?

My ternary operation not equal with this code?

Code:

if($value === 0) $gender = 'Male';
elseif($value === 1) $gender = 'Female';
else $gender = 'Other';
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125
  • 2
    Dont know why, but you should add parantheses for else-if ternary like this: `$value === 0 ? 'Male' : ($value === 1 ? 'Female' : 'Other');` – Code Spirit Sep 05 '19 at 08:26

2 Answers2

4

It's a precedence issue, your code is evaluated as:

$gender = ($value === 0 ? 'Male' : $value === 1) ? 'Female' : 'Other';

but what you want is:

$gender = $value === 0 ? 'Male' : ($value === 1 ? 'Female' : 'Other');

This is because PHP evaluates the ternary operator from left to right. See the manual.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • There're tons of duplicates, yet you decided toi create anoter one. – u_mulder Sep 05 '19 at 08:28
  • @u_mulder I tried googling and SO search but can't find it. Can you close it? – Nick Sep 05 '19 at 08:29
  • 1
    @u_mulder thanks. I have added it to my dupes list. My problem was I only searched for "not working", which brings up a lot of questions which are not the same as this. – Nick Sep 05 '19 at 08:32
0

You need to add some brackets, take reference from here

<?php

$value = 0;
$gender = $value === 0 ? 'Male' : ($value === 1 ?'Female' : ('Other'));
echo $gender;

Check Example: here

Ankur Tiwari
  • 2,762
  • 2
  • 23
  • 40