treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Assigning a Foreach loop...

  • Hi all,

    I'm still new to PHP. I took 5 months at a community college and still don't get everything. Currently I'm trying to make a form mail script with checkboxes. All the other types of inputs are easy, except for this.

    My HTML code is this...

    Have you ever had*:
    Diabetes Hypoglycemia Seizures Fainting Spells Eating Disorders Respiratory Problems Psychiatric Care Phobias

    And my PHP code is this:

    $subject = 'Awe Star Online Missionary Application Form';
    $webMaster = 'email@me.com';
    
    
    $body = <<<EOD
    
    Name - $name
    E-Mail - $email
    
    Have you ever had - $haveyoueverhad
    
    Submitted on:
    $time
    
    EOD;
    
    
    /* Sends E-Mail */
      $headers = "From: $email\r\n";
      $headers . "Content-type: text/html\r\n";
      $success = mail($webMaster, $subject, $body, $headers);
    
    /* Results after E-Mail is sent */
    header('Location:thankyou.php');
    

    Now, learning about checkboxes, I've figured out that I need a foreach loop as checkboxes submit results into an array of values.

      foreach($haveyouever as $haveyouever_result) {
        echo $haveyouever_result)
      }
    

    But, I was wondering, is there a way to output this foreach loop into a variable so I can add that variable into the EOD body for e-mail purposes?

  • I can't seem to add the code feature to the HTML but the name of the checkboxes are $haveyouever[] with a value of whatever it is (not a numerical value)

  • You can use the join() function which accepts a separator then an array.

    $haveyouever = join(', ', $haveyouever);
    
  • I tried putting that inside the foreach loop but it received errors. Is this something I do beforehand?

  • $haveyouever is the array of results from the form submission, correct?

    no, you don't use a loop.


    p.s. join() is an alias for implode()
    (I'd never heard of join() before!)

    p.p.s. - nice to see a college course that teaches using HEREDOC notation! : )

  • That worked beautifully! Thank you guys so much.

    I was googling last night for answers and there were so many if statements and whatnot, I figured it was a lot simpler than 20 lines of code for one checkbox.