php - Foreach duplicating checkbox inputs form
Instead of having 2 inputs with the full-time and the contractor box ticked, I have 4 inputs see below. How can I avoid the duplication of the inputs, and ends up with two inputs only that will have the boxes ticked for full-time and contractor?
Here is the code:
<?php
$jobEmploymentType = "FULL_TIME,CONTRACTOR";
$jobEmploymentTypeExplode = (explode(",",$jobEmploymentType));
//print_r($jobEmploymentTypeExplode);
foreach ($jobEmploymentTypeExplode as $jobType) : ?>
<span class="asterisk">*</span> <label for="jobEmploymentType">Employment Type</label><br>
<input type="checkbox" class="w3-check" id="fullTime" name="fullTime" value="FULL_TIME" <?= ($jobType == "FULL_TIME")? "checked":"";?>>
<label for="fullTime"> FULL-TIME</label><br>
<input type="checkbox" class="w3-check" id="contractor" name="contractor" value="CONTRACTOR" <?= ($jobType == "CONTRACTOR")? "checked":"";?>>
<label for="contractor"> CONTRACTOR</label><br>
<?php endforeach; ?>
Expecting result:
Answer
Solution:
I've found a way that works for me using in_array:
PHP Code:
$jobTypeExplode = (explode(",",$jobEmploymentType));
if(in_array('FULL_TIME',$jobTypeExplode)) {$fulltime = 'FULL_TIME';}
if (in_array('CONTRACTOR',$jobTypeExplode)) {$contractor = 'CONTRACTOR';}
HTML code:
<input type="checkbox" class="w3-check" id="fullTime" name="fullTime" value="FULL_TIME" <?= ($fulltime == "FULL_TIME")? "checked":"";?>>
<label for="fullTime"> FULL-TIME</label><br>
<input type="checkbox" class="w3-check" id="contractor" name="contractor" value="CONTRACTOR" <?= ($contractor == "CONTRACTOR")? "checked":"";?>>
<label for="contractor"> CONTRACTOR</label><br>
Answer
Solution:
$jobEmploymentType = "FULL_TIME,CONTRACTOR";
Your problem is in the above line. When you give two values to the variable $jobEmploymentType the program is going to spit out the program twice.
Source