A more DRY approach might be to use arrays a bit more efficiently, and at the same time create a more reusable functions.
Try and maintain amenities in a single place (maybe even get this from a db table)
"select id, type from amenities order by type"
For now use an array though …
// this could be in an include file ameneties.php
$amenities = array(
'BBQ'
, 'Garage'
, 'Balcony'
, 'Patio'
);
// this could be in an include file outputascheckboxes.php
function outputAsCheckboxes($name, $array, $selected=NULL){
$html = '';
foreach($array as $k => $v){
$html .= '<input type="checkbox" name="'. $name . '[]" value="'. $k ;
if($selected && in_array($k, $selected)){
$html .= ' checked = "checked" ';
}
$html .= '">' . $v .'<br />' . PHP_EOL;
}
return $html;
}
Then you can use the same code in your web form and in your email generator
include 'outputascheckboxes.php';
include 'amenities.php';
// these are the selected items
$selected = array(1,2);
$message .= outputAsCheckboxes('ameneties', $amenities, $selected);
Gives:
<input type="checkbox" name="ameneties[]" value="0">BBQ<br />
<input type="checkbox" name="ameneties[]" value="1 checked = "checked" ">Garage<br />
<input type="checkbox" name="ameneties[]" value="2 checked = "checked" ">Balcony<br />
<input type="checkbox" name="ameneties[]" value="3">Patio<br />
On your webform you can then do:
echo outputAsCheckboxes('ameneties', $amenities);
// no third argument, so show all checkboxes unticked.
Gives
<input type="checkbox" name="ameneties[]" value="0">BBQ<br />
<input type="checkbox" name="ameneties[]" value="1">Garage<br />
<input type="checkbox" name="ameneties[]" value="2">Balcony<br />
<input type="checkbox" name="ameneties[]" value="3">Patio<br />
Doing something similar to the above means you can then:
- Maintain your array in a single place, so its easier to maintain
- Show all selections unchecked on a webpage
- Show selections already made in a webpage
- Show selections already made in an email message
- Reuse the function outputAsCheckboxes() in other projects
There are drawbacks, for example to start adding css types to your checkbox you could add more parameters and so on, but for now I hope this gives you some ideas.