Grow your CSS skills. Land your dream job.

Assigning a Foreach loop…

  • # November 20, 2012 at 4:11 am

    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 = < <

    Name – $name
    E-Mail – $email

    Have you ever had – $haveyoueverhad

    Submitted on:
    $time

    EOD;

    /* Sends E-Mail */
    $headers = “From: $emailrn”;
    $headers . “Content-type: text/htmlrn”;
    $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?

    # November 20, 2012 at 4:16 am

    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)

    # November 20, 2012 at 7:48 am

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

    $haveyouever = join(‘, ‘, $haveyouever);

    # November 20, 2012 at 9:00 am

    I tried putting that inside the foreach loop but it received errors. Is this something I do beforehand?

    __
    # November 20, 2012 at 11:16 am

    `$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! : )*

    # November 20, 2012 at 12:18 pm

    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.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".