Page 1 of 1

"foreach" help needed

Posted: Sun Jan 03, 2010 12:48 pm
by jimandy
Try as I might I can not get this to work. The checkboxes display properly. On submit I should get a list of the position (0, 1, 2) of each or all the boxes that are checked. (If B and C checked should get...
1
2
Instead I get
Notice: Undefined variable: bx in /Applications/MAMP/htdocs/test4.php on line 4

Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/test4.php on line 4
--------------
Here's the code...

Code: Select all

<?php
if (isset($_POST['bx'])){
 
    foreach($bx as $this){print $this."<br>";}
    exit();
    }
?>
 
<html>
<form action="test4.php" method="POST">
 
<?php
$list[]="A";
$list[]="B";
$list[]="C";
$nbrInList=count($list);
    
for ($i=0;$i<=2;$i++)
    {
    print $list[$i];
    print "<input name=\"bx[]\" type=\"checkbox\" value=\"$i\"><br>";
    }
?>
<input type='submit'>
</form>
</html>
As always, your patience with a newbie is appreciated.

Re: "foreach" help needed

Posted: Sun Jan 03, 2010 1:10 pm
by manohoo
$_POST['bx'] is not an array, so you can't use foreach.

However, $_POST is an associative array, maybe this is what you want:

Code: Select all

<?php
if (isset($_POST)){
    foreach($_POST as $key=>$value){print $key." ".$value."<br>";}
}
?>
Notice that I have removed "exit" from your code. You can't have "exit" inside a foreach statement, since it would force to exit the file at the first iteration.

Re: "foreach" help needed

Posted: Sun Jan 03, 2010 1:41 pm
by jimandy
You can't have "exit" inside a foreach statement, since it would force to exit the file at the first iteration.
Yikes, I should know better than that.

Thanks!

Re: "foreach" help needed

Posted: Mon Jan 04, 2010 9:47 am
by AbraCadaver
manohoo wrote:$_POST['bx'] is not an array, so you can't use foreach.
Actually, if you look at the code, $_POST['bx'] is an array, but $bx is not, it's Undefined.

Re: "foreach" help needed

Posted: Mon Jan 04, 2010 10:07 am
by jimandy
I see the error. Works now that I have inserted on line 3..

$bx=$_POST['bx'];

Thanks for ya'll's replies.