Search code examples
phpselected

PHP Preselect check boxes from a String


I have a string $eventdays which holds information regarding which days are selected.

The format of the data is:

Monday = Mo 
Tuesday = Tu
Wedneday = We
Thursday = Th
Friday = Fr
Saturday = Sa
Sunday = Su

Mo,Tu,We,Th,Fr,Sa,Su

So if for example Tuesday and Friday were selected, the string would be:

Tu,Fr

If Monday, Wednesday, and Saturday were selected it would be:

Mo,We,Sa

Note: Any combination of days can be selected.

I was wondering how to get this information, and preselect checkboxes. The checkboxes are:

<input type="checkbox" name="days[]" value="Mo" />Monday<br />
<input type="checkbox" name="days[]" value="Tu" />Tuesday<br />
<input type="checkbox" name="days[]" value="We" />Wednesday<br />
<input type="checkbox" name="days[]" value="Th" />Thursday<br />
<input type="checkbox" name="days[]" value="Fr" />Friday<br />
<input type="checkbox" name="days[]" value="Sa" />Saturday<br />
<input type="checkbox" name="days[]" value="Su" />Sunday<br />

I know how to preselect a checkbox (checked = "yes"), but my question is how can I parse the string and then select the correct checkboxes from that information?


Solution

  • You can use strpos and dynamically generate your checkboxes.

    $eventdays = "Tu,Fr"; // Selected days
    
    $days = array( "Monday"   => "Mo",
                   "Tuesday"  => "Tu",
                   "Wedneday" => "We",
                   "Thursday" => "Th",
                   "Friday"   => "Fr",
                   "Saturday" => "Sa",
                   "Sunday"   => "Su"
                );
    
    foreach ($days AS $day => $shortDay) {
        // Is there an event on this day?
        $checked = strpos($eventdays, $shortDay) !== FALSE ? "checked='checked'" : "";
        // Generate checkbox HTML
        echo "<input type='checkbox' name='days[]' value='{$shortDay}' {$checked} />{$day}<br />"; 
    }
    

    Output

    <input type='checkbox' name='days[]' value='Mo' />Monday<br />
    <input type='checkbox' name='days[]' value='Tu'  checked='checked'/>Tuesday<br />
    <input type='checkbox' name='days[]' value='We' />Wedneday<br />
    <input type='checkbox' name='days[]' value='Th' />Thursday<br />
    <input type='checkbox' name='days[]' value='Fr'  checked='checked'/>Friday<br />
    <input type='checkbox' name='days[]' value='Sa' />Saturday<br />
    <input type='checkbox' name='days[]' value='Su' />Sunday<br />