nested for loop

General discussions related to php

Moderators: macek, egami, gesf

tony09uk
New php-forum User
New php-forum User
Posts: 3
Joined: Mon Nov 05, 2012 2:11 pm

nested for loop

Postby tony09uk » Tue Nov 06, 2012 2:15 pm

I have an issue with a nested for loop. I have created a form that passes information to another page to echo out then put into a database. My problem is that the for loop on page two doesn't work how I expected it to work and after two hours of playing with alternative options ive given up.

On a previous page I have allowed the user to choose how many questions and how many choices for each question they want.

PAGE 1

Code: Select all

echo "<h1>Change the values in each box</h1>\n";//title
             
            echo "<form method=\"post\" action=\"addToDb.php\">\n";//start form

            for($q = 1; $q <= $questions; $q++){//loop through number of questions required
                 
                echo "  <input name='questions[]' type='text' value='question $q' /><br/>\n";
             
                for($opt = 1; $opt <= $choices; $opt++){//loop through number of options required

                   echo "   <input name='choice[]' type='text' value='option $opt' /><br/>\n";
                   
                }
                 
            }
             
            echo "  <input name='submit' type='submit' value='SUBMIT' />\n";//submit form
            echo "</form>";//close form 


Page 2

Code: Select all

$q = $_POST['questions'];
    $c = $_POST['choice'];
     
    foreach($q AS $v){
        echo $v . "<br/>\n";
        foreach($c AS $value){
            echo "  " . $value . "<br/>\n";
        }
         
         
    } 


My problem is that the second for loop on page two seems to run through all the choices before moving on to question 2

EXAMPLE - what I want

Q1
C1
C2
C3
C4

Q2
C1
C2
C3
C4

Q3
C1
C2
C3
C4

EXAMPLE - what I GET

Q1
C1
C2
C3
C4
C1
C2
C3
C4
C1
C2
C3
C4

Q2
C1
C2
C3
C4
C1
C2
C3
C4
C1
C2
C3
C4

Q3
C1
C2
C3
C4
C1
C2
C3
C4
C1
C2
C3
C4

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: nested for loop

Postby seandisanti » Wed Nov 07, 2012 3:19 pm

you could just do it this way; ( i hardcoded 4's instead of recreating post values, so just replace them with your values)

Code: Select all

<?php

   for ($q=1;$q<=4;$q++) {
      echo 'Q'.$q.'<br />';
      for ($c=1;$c<=4;$c++){
         echo 'C'.$c.'<br />';
      }
   }

tony09uk
New php-forum User
New php-forum User
Posts: 3
Joined: Mon Nov 05, 2012 2:11 pm

Re: nested for loop

Postby tony09uk » Wed Nov 07, 2012 4:00 pm

Can you explain a little further please? I understand the 4 has replaced $_POST['c'] but I thought when a post variable was passed, it is passed as an array therefore requiring a foreach loop to dissect what it in that array and output it accordingly?


Return to “PHP General”

Who is online

Users browsing this forum: Yahoo [Bot] and 1 guest