为什么Checked属性不适用于使用PHP的单选按钮?

Here is my code snippet:

echo "<tr>
    <td>Fruits</td>
    <td>
    <input type='radio' name='fruit' value='Apple'    ($fruit=='Apple')?'checked':''> Apple
    <input type='radio' name='chamber' value='Banana' ($fruit=='Banana')?'checked':''> Banana</td>
    </tr>";

Value of $fruit is Apple but still the the radio button attribute is not being set to checked.

If you check the output of this you can see that the statement will not execute as you want because it's inside the " ". You need to break the " before and continue after the check like this:

echo "<tr>
 <td>Fruits</td>
 <td>
 <input type='radio' name='fruit' value='Apple'  " .  (($fruit=='Apple')?'checked="checked"':'') . "> Apple
 <input type='radio' name='chamber' value='Banana' " .(($fruit=='Banana')?'checked="checked"':'') . "> Banana</td>
</tr>";

And better to include all inside brackets (...) to not mess with something else.

Also it's better to have checked="checked" when you want to mark something as checked.

In your example either you can add ?'checked':'' inside the ($fruit=='Apple') or add one more bracket for all ternary.

Example (it's better to use <?php ?> where you need):

<tr>
<td>Fruits</td>
<td>
<input type='radio' name='fruit' value='Apple' <?=($fruit=='Apple' ? 'checked' : '')?>> Apple
<input type='radio' name='fruit' value='Banana' <?=($fruit=='Banana' ? 'checked' : '')?>> Banana</td>
</tr>

Easiest wasy if any problem is found:

if($fruit=='Apple') $check="checked"; else $check="";
if($fruit=='Banana') $check="checked"; else $check="";
    
echo "<tr>
 <td>Fruits</td>
 <td>
 <input type='radio' name='fruit' value='Apple'  " .$check. "> Apple
 <input type='radio' name='chamber' value='Banana' " .$check. "> Banana</td>
</tr>";

</div>