"foreach" help needed

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jimandy
Forum Newbie
Posts: 22
Joined: Sat Sep 15, 2007 10:56 am
Location: Alabama, USA

"foreach" help needed

Post 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.
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: "foreach" help needed

Post 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.
jimandy
Forum Newbie
Posts: 22
Joined: Sat Sep 15, 2007 10:56 am
Location: Alabama, USA

Re: "foreach" help needed

Post 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!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: "foreach" help needed

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
jimandy
Forum Newbie
Posts: 22
Joined: Sat Sep 15, 2007 10:56 am
Location: Alabama, USA

Re: "foreach" help needed

Post by jimandy »

I see the error. Works now that I have inserted on line 3..

$bx=$_POST['bx'];

Thanks for ya'll's replies.
Post Reply