mach2
mach2

Reputation: 460

check the radio button based in the output of if condition in php

I searched for the answer everywhere, although similar questions are already there on stackoverflow i did not find a satisfactory answer.

Following are the question i've referred,

checked the radio button based on the ajax response

Check the radio button based on the value fetched from mysql database

What i have is data coming in from model in object $data.

So i fetch it in my view like $data->is_male.

What i want is if($data->is_male == 1) then check the button,

<input type="radio" name="gender" value=

              <?php if ($data->is_male == 1): ?>
                                    'checked'
              <?php endif ?>> Male<br>

<input type="radio" name="gender" value="female"> Female<br>

Upvotes: 1

Views: 6697

Answers (2)

Ahmed Numaan
Ahmed Numaan

Reputation: 1062

Below is a more readable answer. I have used PHP ternary conditional operator here.

<input type="radio" name="gender" value="male" <?php echo ($data->is_male==1) ? 'checked="checked"':'';?>>Male
<br>

<input type="radio" name="gender" value="female"> Female
<br>

Upvotes: 1

Ankur Sharma
Ankur Sharma

Reputation: 187

Try this:-

<input type="radio" name="gender" value="male" 
    <?php if ($data->$data->is_male == 1): ?>
               checked="checked"
    <?php endif ?>> Male<br>

<input type="radio" name="gender" value="female"> Female<br>

Upvotes: 2

Related Questions