Results 1 to 2 of 2

Thread: foreach array only returns one result

  1. #1
    Join Date
    Mar 2007
    Location
    New York, NY
    Posts
    557
    Thanks
    8
    Thanked 66 Times in 66 Posts

    Default foreach array only returns one result

    Aloha!

    I have foreach() to parse each checkbox value a user selects separately. It worked fine before I used it in an IF expression-but now it's not. Without the IF, if the user doesn't select any checkbox and DOES submit the form, the foreach won't recognize any data (obviously) and will return w/an error. Below is the code of the page:

    PHP Code:
    <?php

    $a 
    $_GET['a'];

    if(
    $a == 'a') {

    $state $_POST['state'];


    if(!
    $state) {



    echo 
    "<font color=red>Please select a state</font>";

    } else {
    foreach (
    $state as $statename);
    {
    echo 
    "$statename is checked";
    }

    }


    }

    ?>
    <form action="test.php?a=a" method="post">
    <input type="checkbox" value="New York" name="state[]">New York<br />
    <input type="checkbox" value="Maryland" name="state[]">Maryland<br />
    <input type="submit">
    </form>
    Thanks!
    - Josh

  2. #2
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    PHP Code:
    $state $_POST['state']; //set state to something even if null (probably with a warning
    if(!$state) { //now, regardless of the form, it has the value of $_POST['state'], or null
    //this is always true 
    Daniel - Freelance Web Design | <?php?> | <html>| español | Deutsch | italiano | português | català | un peu de français | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •