How to convert if statement to ternary?

This is the code

<?php 
if($gender === 'm'){
echo ' checked';} 
?>

When I am trying to convert it to ternary
<?php $gender === 'm' ? ' checked' ; ?> // without else, it can't work

Is ternary required ELSE statement, I don’t want to use else statement

Try this :slight_smile:

<?php echo ($gender === 'm') ? 'Checked' : NULL; 
1 Like

Nope, I had already tried that option but doesn’t work.

What @John_Betong has given you is the right format for a ternary operator, so perhaps you need to look at why it’s not working.

What do you get if you echo ($gender === 'm'); ?

1 Like

Try replacing NULL with $gender;

If and only if you are using PHP 7 try using the Null coalescing operator

http://php.net/manual/en/migration70.new-features.php

.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.