Home > Mobile >  Using foreach loop to echo array values in PHP
Using foreach loop to echo array values in PHP

Time:02-02

I have a html form with the following input tags

<input type="text" name="parcelnumber[]" id="parcelnumber"  placeholder="Parcel Number">
<input type="text" name="section[]" id="section"  placeholder="Section">

The html form looks like so; enter image description here

The user is given the ability to dynamically add extra parcel numbers.

How can I use a foreach loop to echo each Section for each Parcel numbers?

The below foreach loop is not giving me the results I want. The last section is repeated again for the first parcel loop. That is why it is not giving me the echo result I am after.

$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $parcel) {
    foreach ($sections as $section) { }
    echo $parcel . $section . "<br>";       
}

CodePudding user response:

If I understand correctly, does this help?

$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $key => $parcel) {
    echo $parcel . " - " . $sections[$key] . "<br>";       
}

CodePudding user response:

Currently the code will just iterate over all parcels and all sections. You need to define the sections for each parcel, it should be like this

<input type="text" name="parcelnumber[]" id="parcelnumber"  placeholder="Parcel Number">
<input type="text" name="section[parcelnumber][]" id="section"  placeholder="Section">

Change the name attribute of the section input with js, so that you can map which section belongs to which parcel

and then use,

$parcels = $_POST['parcelnumber'];
$sections = $_POST['section'];

foreach($parcels as $parcel) {
    foreach ($sections[$parcel] as $section) { }
    echo $parcel . $section . "<br>";       
}
  •  Tags:  
  • Related