0

I have a html form with the following input tags

<input type="text" name="parcelnumber[]" id="parcelnumber" class="gui-input" placeholder="Parcel Number">
<input type="text" name="section[]" id="section" class="gui-input" 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>";       
}

2 Answers 2

2

If I understand correctly, does this help?

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

foreach($parcels as $key => $parcel) {
    echo $parcel . " - " . $sections[$key] . "<br>";       
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tested your answer and it sure does give me the result I am after.
CharlesEF your answer worked perfect for me. Wish I could upvote a thousand times. Thanks alot.
Glad it worked out for you.
0

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" class="gui-input" placeholder="Parcel Number">
<input type="text" name="section[parcelnumber][]" id="section" class="gui-input" 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>";       
}

3 Comments

Thanks. I will test your answer and get back.
I ran your code but a number of errors were returned. I am using PHP 7.2. I also changed the html attributes as you suggested.
<input type="text" name="section['the parcel number'][0]" id="section" class="gui-input" placeholder="Section"> <input type="text" name="section['the parcel number'][1]" id="section" class="gui-input" placeholder="Section"> The parcel number will be added dynamically in the name attribute in 'the parcel number' position.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.