#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    8
    Rep Power
    0

    Foreach loop not working as expected


    I have created some code that dynamically generates a form which the user can fill in. Once this is done they are sent to another page and a preview is outputted for review, before they submit it to a database.

    The code is as follows:

    PHP Code:

    $questions 
    3;
    $choices 2;

            if(isset(
    $questions) && isset($choices)){//choices and question number selected
                
                
    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
                            
            

    On submitting they are sent to addToDb.php (It is this section that does not output the questions and options correctly.....why?)

    PHP Code:

            $q 
    $_POST['questions'];
            
    $c $_POST['choice'];

            foreach(
    $q AS $v){

                echo 
    $v "<br/>\n";
                foreach(
    $c AS $value){
                    echo 
    "  " $value "<br/>\n";
                }       

            } 

    The code I have written output one $q variable, then all the $c variables before outputting the next $q variable.

    How come the script is not linking the which choices are relevant to which questions?

    I have tried several ways and failed each time, can someone please help?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Sep 2006
    Posts
    1,928
    Rep Power
    533
    On the top of the second script, and add:
    PHP Code:
    echo('<pre>.print_r($q,1).'</pre>');
    echo('
    <pre>.print_r($c,1).'</pre>'); 
    What do you see? Not what you wanted, is it.

    On your first screen, now try changing
    PHP Code:
    echo "   <input name='choice[$q-1][]' type='text' value='option $opt' /><br/>\n"
  4. #3
  5. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    Not sure if the following is helpful, but I'll post anyway

    PHP Code:
    foreach ($_POST['questions'] as $key => $something) {
        echo 
    $something;
        foreach (
    $_POST['choice'][$key] as $choice) {
            echo 
    $choice;
        }

  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by NotionCommotion
    On the top of the second script, and add:
    PHP Code:
    echo('<pre>.print_r($q,1).'</pre>');
    echo('
    <pre>.print_r($c,1).'</pre>'); 
    What do you see? Not what you wanted, is it.

    On your first screen, now try changing
    PHP Code:
    echo "   <input name='choice[$q-1][]' type='text' value='option $opt' /><br/>\n"
    *this reply has been edited*

    Thanks for the response, you are correct I did not get what I wanted, it was two separate arrays containing question[] and choice[] respectfully.

    I have now implement the code you offered and it seems to be working, however, I am not fully sure what is happening with the code you posted so I am unable to create a working loop.

    AndrewSW has kindly posted some generic code that seems to be the answer, BUT, i don't understand your code so I can't put it into practice.

    Can you direct me to a tutorial so I can fill in missing knowledge or give me a quick explanation of what it is doing and how to access it with the loop?

    many thanks
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by AndrewSW
    Not sure if the following is helpful, but I'll post anyway

    PHP Code:
    foreach ($_POST['questions'] as $key => $something) {
        echo 
    $something;
        foreach (
    $_POST['choice'][$key] as $choice) {
            echo 
    $choice;
        }

    Thanks AndrewSW I tried the code you posted, but it did not work for me :s
    Was I meant to replace [$key] with something? Or was your code taking into account the code that was posted above? As I am sure you have read, I couldn't make that work for some reason
  10. #6
  11. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    @tony09uk
    The code I posted was just a sample and I don't know if it applies directly to your current code - sorry if it confuses. I should have deleted it
    [But $key would not need to be changed.]
    Last edited by AndrewSW; December 1st, 2012 at 04:32 PM.
  12. #7
  13. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    I'm regretting mentioning this as I'm still not sure whether the following is helpful. But,

    PHP Code:
    <?php
    // Assuming $questions and $choice have the same length..
    $questions = array("hello""one""two");
    $choice = array();
    $choice[0] = array("hi 1"1"third""fourth");
    $choice[1] = array("hi 2"2"third""fourth");
    $choice[2] = array("hi 3"3"third""fourth");

    foreach (
    $questions as $key => $something) { 
        echo 
    "<p>" $something "</p><p>"
        foreach (
    $choice[$key] as $achoice) { 
            echo 
    $achoice " "
        }
        echo 
    "</p>";
    }
    ?>
    produces the output
    hello

    hi 1 1 third fourth

    one

    hi 2 2 third fourth

    two

    hi 3 3 third fourth
    but feel free to ignore this if it is not helpful .
    Last edited by AndrewSW; December 1st, 2012 at 05:12 PM. Reason: /p in wrong place
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by AndrewSW
    I'm regretting mentioning this as I'm still not sure whether the following is helpful. But,

    PHP Code:
    <?php
    // Assuming $questions and $choice have the same length..
    $questions = array("hello""one""two");
    $choice = array();
    $choice[0] = array("hi 1"1"third""fourth");
    $choice[1] = array("hi 2"2"third""fourth");
    $choice[2] = array("hi 3"3"third""fourth");

    foreach (
    $questions as $key => $something) { 
        echo 
    "<p>" $something "</p><p>"
        foreach (
    $choice[$key] as $achoice) { 
            echo 
    $achoice " "
        }
        echo 
    "</p>";
    }
    ?>
    produces the output

    but feel free to ignore this if it is not helpful .
    Andrew, thanks for the help. It is really appriciated and I think it will be of use once I can learn to understand working with multidimensional arrays in forms
  16. #9
  17. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    If you use

    PHP Code:
    echo('<pre>.print_r($q,1).'</pre>'); 
    echo('
    <pre>.print_r($c,1).'</pre>'); 
    as suggested by NotionCommotion then this will give you a better idea of what you are trying to examine/loop through.

    Good luck
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    8
    Rep Power
    0
    Originally Posted by AndrewSW
    If you use

    PHP Code:
    echo('<pre>.print_r($q,1).'</pre>'); 
    echo('
    <pre>.print_r($c,1).'</pre>'); 
    as suggested by NotionCommotion then this will give you a better idea of what you are trying to examine/loop through.

    Good luck
    Okay, i will get to it. I had already spent some time staring at it but came up with nothing , having said that i was quite tired. I will have another go later, thanks to both of you for your help
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Sep 2006
    Posts
    1,928
    Rep Power
    533
    What you are working with are multidimensional arrays. When you post or get something who's name ends in [], you are just telling PHP to make an array out of it. Note that starting your arrays at zero will give you less surprises. Play around with the following. Try changing the names and including or not including an index number (i.e. change value="'.$answers[$a].'" to value="'.$answers[].'"). Also, use print_r() often. I swear by it. The <pre> tags make it much easier to read.


    PHP Code:
    <?php
        
    if(isset($_POST['submit']))
        {
            echo(
    '<pre>'.print_r($_POST,1).'</pre>');
        }

        
    $questions=array(
            
    'How old would you be if you didnít know how old you are?',
            
    'Which is worse, failing or never trying?',
            
    'If life is so short, why do we do so many things we donít like and like so many things we donít do?',
            
    'When itís all said and done, will you have said more than youíve done?',
            
    'What is the one thing youíd most like to change about the world?',
            
    'If happiness was the national currency, what kind of work would make you rich?',
            
    'Are you doing what you believe in, or are you settling for what you are doing?',
            
    'If the average human life span was 40 years, how would you live your life differently?',
            
    'To what degree have you actually controlled the course your life has taken?',
            
    'Are you more worried about doing things right, or doing the right things?',
            
    'Youíre having lunch with three people you respect and admire.* They all start criticizing a close friend of yours, not knowing she is your friend.* The criticism is distasteful and unjustified.* What do you do?',
            
    'If you could offer a newborn child only one piece of advice, what would it be?',
            
    'Would you break the law to save a loved one?',
            
    'Have you ever seen insanity where you later saw creativity?',
            
    'Whatís something you know you do differently than most people?',
            
    'How come the things that make you happy donít make everyone happy?',
            
    'What one thing have you not done that you really want to do?* Whatís holding you back?',
            
    'Are you holding onto something you need to let go of?',
            
    'If you had to move to a state or country besides the one you currently live in, where would you move and why?',
            
    'Do you push the elevator button more than once?* Do you really believe it makes the elevator faster?',
            
    'Would you rather be a worried genius or a joyful simpleton?',
            
    'Why are you, you?',
            
    'Have you been the kind of friend you want as a friend?',
            
    'Which is worse, when a good friend moves away, or losing touch with a good friend who lives right near you?',
            
    'What are you most grateful for?',
            
    'Would you rather lose all of your old memories, or never be able to make new ones?',
            
    'Is is possible to know the truth without challenging it first?',
            
    'Has your greatest fear ever come true?',
            
    'Do you remember that time 5 years ago when you were extremely upset?* Does it really matter now?',
            
    'What is your happiest childhood memory?* What makes it so special?',
            
    'At what time in your recent past have you felt most passionate and alive?',
            
    'If not now, then when?',
            
    'If you havenít achieved it yet, what do you have to lose?',
            
    'Have you ever been with someone, said nothing, and walked away feeling like you just had the best conversation ever?',
            
    'Why do religions that support love cause so many wars?',
            
    'Is it possible to know, without a doubt, what is good and what is evil?',
            
    'If you just won a million dollars, would you quit your job?',
            
    'Would you rather have less work to do, or more work you actually enjoy doing?',
            
    'Do you feel like youíve lived this day a hundred times before?',
            
    'When was the last time you marched into the dark with only the soft glow of an idea you strongly believed in?',
            
    'If you knew that everyone you know was going to die tomorrow, who would you visit today?',
            
    'Would you be willing to reduce your life expectancy by 10 years to become extremely attractive or famous?',
            
    'What is the difference between being alive and truly living?',
            
    'When is it time to stop calculating risk and rewards, and just go ahead and do what you know is right?',
            
    'If we learn from our mistakes, why are we always so afraid to make a mistake?',
            
    'What would you do differently if you knew nobody would judge you?',
            
    'When was the last time you noticed the sound of your own breathing?',
            
    'What do you love?* Have any of your recent actions openly expressed this love?',
            
    'In 5 years from now, will you remember what you did yesterday?* What about the day before that?* Or the day before that?',
            
    'Decisions are being made right now.* The question is:* Are you making them for yourself, or are you letting others make them for you?'
        
    );
        
    $answers=array('Yes','No','Maybe','I don\t know');

        echo(
    '<form method="post" action="'.$_SERVER['PHP_SELF'].'"><ul>');
        for(
    $q 0$q <= count($questions)-1$q++)
        {
            echo(
    '<li><input name="questions['.$q.']" type="text" value="'.$questions[$q].'" /><ul>');
            for(
    $a 0$a <= count($answers)-1$a++)
            {
                echo(
    '<li><input name="answers['.$q.'][]" type="text" value="'.$answers[$a].'" /></li>');
            }
            echo(
    '</ul>');
        }
        echo(
    '</ul><input name="submit" type="submit" value="SUBMIT" /></form>');
    ?>

IMN logo majestic logo threadwatch logo seochat tools logo