PHP HTML Dynamic Checkbox From Array
From w3cyberlearnings
Contents |
PHP Dynamic HTML Checkbox from Array
Make HTML Checkbox From Array.
Example 1: Normal Array
<?php $array = array('BMW', 'Ford', 'Honda', 'Toyota', 'Lexus', 'KIA', 'SCION'); for ($i = 0; $i < count($array); $i++) { echo "<input type=\"checkbox\" name=\"car[]\" value=\"{$array[$i]}\" id=\"id{$array[$i]}\"/>"; echo "<label for=\"id{$array[$i]}\">$array[$i]</label>"; } ?>
Output
<input type="checkbox" name="car[]" value="BMW" id="idBMW"/> <label for="idBMW">BMW</label> <input type="checkbox" name="car[]" value="Ford" id="idFord"/> <label for="idFord">Ford</label> <input type="checkbox" name="car[]" value="Honda" id="idHonda"/> <label for="idHonda">Honda</label> <input type="checkbox" name="car[]" value="Toyota" id="idToyota"/> <label for="idToyota">Toyota</label> <input type="checkbox" name="car[]" value="Lexus" id="idLexus"/> <label for="idLexus">Lexus</label> <input type="checkbox" name="car[]" value="KIA" id="idKIA"/> <label for="idKIA">KIA</label> <input type="checkbox" name="car[]" value="SCION" id="idSCION"/> <label for="idSCION">SCION</label>
Example 2: Associative Array
<?php $array = array( 'c1' => 'BMW', 'c2' => 'Ford', 'c3' => 'Honda', 'c4' => 'Toyota', 'c5' => 'Lexus', 'c6' => 'KIA', 'c7' => 'SCION'); foreach ($array as $value=>$label) { echo "<input type=\"checkbox\" name=\"car[]\" value=\"{$value}\" id=\"id{$value}\"/>"; echo "<label for=\"id{$value}\">{$label}</label>"; } ?>
Output: HTML Source
<input type="checkbox" name="car[]" value="c1" id="idc1"/> <label for="idc1">BMW</label> <input type="checkbox" name="car[]" value="c2" id="idc2"/> <label for="idc2">Ford</label> <input type="checkbox" name="car[]" value="c3" id="idc3"/> <label for="idc3">Honda</label> <input type="checkbox" name="car[]" value="c4" id="idc4"/> <label for="idc4">Toyota</label> <input type="checkbox" name="car[]" value="c5" id="idc5"/> <label for="idc5">Lexus</label> <input type="checkbox" name="car[]" value="c6" id="idc6"/> <label for="idc6">KIA</label> <input type="checkbox" name="car[]" value="c7" id="idc7"/> <label for="idc7">SCION</label>
Related Links
Dynamic HTML From Array
- Dynamic Drop Down List with Array
- Dynamic List with Array
- Dynamic Radio with Array
- Dynamic Checkbox with Array
Dynamic HTML From Database
Dynamic HTML with Ajax
Others Related