Ramesh Ramesh - 6 months ago 15
PHP Question

$_POST inside for loop returning null

I'm trying to loop through the

$_POST['job-destination[$i]']
, however its returning null when I did
$i = 0; var_dump($_POST['job-destination[$i]']);


PHP code

// Experience loop
$experience = '';

for ($i=0; $i <= 10; $i++){
$experience .="<h4>Experience $i: </h4>
<b>Destination</b>: ".$_POST['job-destination[$i]']."<br/>";
}


HTML Code

<div class="form-group">
<p>Destination</p>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[0]" value="Australia" type="radio" required="">
<label for="job-destination">Australia</label>
</div>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[0]" value="Canada" type="radio">
<label for="job-destination">Canada</label>
</div>
</div>
<div class="form-group">
<p>Destination</p>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[1]" value="Australia" type="radio" required="">
<label for="job-destination">Australia</label>
</div>
<div class="radio-btn-grp">
<input class="job-destination" name="job-destination[1]" value="Canada" type="radio">
<label for="job-destination">Canada</label>
</div>
</div>

Answer

PHP

Replace this :

$_POST['job-destination[$i]']

with this :

$_POST['job-destination'][$i]

In your HTML inputs, using [] like so will automatically indexing your input :

HTML

 <div class="form-group">
  <p>Destination</p>
  <div class="radio-btn-grp">
    <input class="job-destination" name="job-destination[]" value="Australia" type="radio" required="">
    <label for="job-destination">Australia</label>
  </div>
  <div class="radio-btn-grp">
    <input class="job-destination" name="job-destination[]" value="Canada" type="radio">
    <label for="job-destination">Canada</label>
  </div>
</div>

you should also change your for loop to iterate your $_POST['job-destination']

PHP

for ($i=0; $i <= count($_POST['job-destination']); $i++){