0

I have this php echo statement for a checkbox that is in a loop:

echo "<input name='battery[$i]' type='checkbox' id='battery[$i]' value='Yes' style='margin-top:10px; margin-left:15px;' />";

I would like to add this condition to it based on a query result:

<?php if($rowbill['battery'] == "Yes") print "checked"; ?>

But I am having a hard time getting the correct syntax for the concatenate, please some help would be appreciated.

Renee Cribe
  • 325
  • 1
  • 4
  • 14

3 Answers3

5

Try this:

echo "<input name='battery[$i]'" .($rowbill['battery'] == "Yes" ? "checked='checked'" : ""). " type='checkbox' id='battery[$i]' value='Yes' style='margin-top:10px; margin-left:15px;' />";
Nic
  • 581
  • 2
  • 11
2

For readability, I prefer set before a var

$checked = $rowbill['battery'] == "Yes"? ' checked="checked"' : '';

and after:

echo "<input name='battery[$i]' type='checkbox' id='battery[$i]' value='Yes' style='margin-top:10px; margin-left:15px;'$checked />";

Otherwise, only in one

echo "<input name='battery[$i]' type='checkbox' id='battery[$i]' value='Yes' style='margin-top:10px; margin-left:15px;'".($rowbill['battery'] == "Yes"? ' checked="checked"' : '')." />";
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
1

Try this:

 '<input name="'.battery[$i].'" type="checkbox" id="'.battery[$i].'" value="Yes" style="margin-top:10px; margin-left:15px;"'.($rowbill['battery'] == 'Yes' ? ' checked="checked"' : '').'>';

Note how using '' delimiters makes it easier to concatenate when you need to use "" as part of your output.

Boaz
  • 19,892
  • 8
  • 62
  • 70
  • thank you for the tip. ill start using ' as my delimiter going forward as i do see how its easier to concatenate with it – Renee Cribe Jan 05 '13 at 23:35
  • I agree with @Boaz regarding the delimiters. But remember that this also means you have to concat if you want to use variables inside the string. Anyway, there might be a slight performance gain using `''` as well, because PHP doesn`t have to check for code inside the string. – Nic Jan 05 '13 at 23:38
  • 1
    More on this topic in [this nice post](http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php). – Boaz Jan 05 '13 at 23:44