genius genius - 5 months ago 17
HTML Question

Ternary operator on Radio Button

I am new to PHP/Programming. I am unable to understand this ternary operator condition used for radio buttons. Can anyone tell me how do I convert this to simple

if else
type condition.?

<?php if($_POST['midnightdelivery'])
{
echo ($_POST['midnightdelivery'] == 0)?'checked="checked"':'';
}
else
{
echo 'checked="checked"';
}
?>


I checked this This for understanding ternary Operator. But I couldn't understand same operator in mine case.

Update:Also can someone give me an example of
if-elseif -else
to ternary opertaor?

Answer

I think below code will help you to understand ternary operator......

below code is for current_file.php using if elseif else.....

    <?php
    if(isset($_POST["submit"]))
    {
        $gender = $_POST['gender'];
        if($gender == male)
        {
            $selected_radio_button = "checked='checked'";
        }
        elseif($gender == female)
        {
            $selected_radio_button = "checked='checked'";
        }
        else
        {
            $selected_radio_button = "";
        }
        ?>
        <form action="#">
            <input type='radio' name='gender' value='male' <?php echo $selected_radio_button; ?>> Male
            <input type='radio' name='gender' value='female' <?php echo $selected_radio_button; ?>> Female
            <input type='submit' name='submit' value='Submit'>
        </form>
        <?php
    }
    else
    {
    ?>
    <form name='rform' method='post' action='current_file.php'>
         <input type='radio' name='gender' value='male'> Male
         <input type='radio' name='gender' value='female'> Female
         <input type='submit' name='submit' value='Submit'>
    </form>
<?php
    }
?>

Now, below code is for current_file.php using ternary operator......

    <?php
    if(isset($_POST["submit"]))
    {
        $gender = $_POST['gender'];
        ($gender == "male" || $gender == "female") ? $selected_radio_button = "checked='checked'" : $selected_radio_button = "";
        ?>
        <form action="#">
            <input type='radio' name='gender' value='male' <?php echo $selected_radio_button; ?>> Male
            <input type='radio' name='gender' value='female' <?php echo $selected_radio_button; ?>> Female
            <input type='submit' name='submit' value='Submit'>
        </form>
        <?php
    }
    else
    {
    ?>
    <form name='rform' method='post' action='current_file.php'>
         <input type='radio' name='gender' value='male'> Male
         <input type='radio' name='gender' value='female'> Female
         <input type='submit' name='submit' value='Submit'>
    </form>
<?php
    }
?>

Both servers same result but ternary operator use less line of code.... Hope this will help you...

Comments