Marilee
Marilee

Reputation: 1598

undefined index invalid argument for loop error

Please point me in the right direction here Im trying to do the following:

  1. Multiple select boxes are generated for each eventid
  2. User choose who they think will win each event
  3. The name of each selectBox is the event id assigned to variable $id
  4. At end of while loop I want to extract the array $id value in For loop, however im getting error "undefined offset & invalid argument" on my for loop...

Here is my form

enter image description here

    $i=0;//counter
    while($row=mysql_fetch_array($result)){

    $team1 = $row['team1'];
    $team2 = $row['team2'];
    $id[$i]= $row['event_id']; 

    echo'<h3>'.$team1.' VS '.$team2.'</h3>';
    echo'<select name="'.$id[$i].'">';
            echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
            echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
            echo'</select>';    
        $i++;
    }//while

Here is my for loop giving error, I suspect problem is in the $_POST['$id']...

if(isset($_POST['submit'])){    

    foreach($_POST[$id] as $eventId => $winner){
     echo'<h3>'.$eventId.'</h3>';
}//for loop
}//end isset

Any help will be greatly appreciated

Upvotes: 0

Views: 196

Answers (2)

earl
earl

Reputation: 36

You don't know what the event_id values are on the action page, so I think you'll have to query for those again something like:

if(isset($_POST['submit'])){
    /* do your query here */
    $data = array();
    while($row=mysql_fetch_array($result)){
     $data[] = $_POST[$row['event_id']];
    }

    foreach($data as $key => $value){
        print_r($_POST[$value]);
        echo "<br>";
    }
}

Upvotes: 0

Digits
Digits

Reputation: 2684

$id is defined as an array here$id[$i]= $row['event_id'];. Arrays can not be used as a key in a foreach array or otherwise. This is what is causing you an error on this line

foreach($_POST[$id] as $eventId => $winner){ //$id is an array of values
    echo'<h3>'.$eventId.'</h3>';
}//for loop

You have to make a second foreach statement for the $id then use the id values in your current foreach statement.

foreach( $id as $key => $val ) {
foreach( $_POST[$val] as $eventId => $winner){

Upvotes: 2

Related Questions