Cain Nuke Cain Nuke - 6 months ago 18
PHP Question

How to use echo along with shorthand IF, ELSEIF and ELSE

Hi,

I saw somebody else asked this before but the answers there are not what I am looking for. I would like to know what is the shorthand for expressions like this example:

if ($gender == 'male'){
echo 'M;
} else if($gender == 'female'){
echo 'F';
} else {
echo 'undefined';
}


I only know what to do when there is only 2 possibilities:

echo ($gender == 'male' ? 'M' : 'F');


but what about when you have else if like in my example above?

Thank you.

Answer

Check the variable again if the statement is false and you need to add parenthesis around the entire else block

echo ($gender == 'male') ? 'M' : (($gender == 'female') ? 'F' : 'undefined');
Comments