problem with array in html <option> form

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
ant_sutton
Forum Commoner
Posts: 32
Joined: Thu May 05, 2005 5:27 am

problem with array in html <option> form

Post by ant_sutton »

Hi guys. I am reading the learning php5 book and the following bit of code is used in one of the examples. However, when I run it I get the error:

Warning: Invalid argument supplied for foreach() in C:\wamp\www\Tests\test.php on line 40

I can select a single value from the option box and it will print it but I can't select multiple options and print them all by using the foreach function.

ANy idea why this is?

thanks alot

Code: Select all

<form method="POST" action="test.php">

<select name="lunch[]" multiple>

<option value="pork">BBQ Pork Bun</option>

<option value="chicken">Chicken Bun</option>

<option value="lotus">Lotus Seed Bun</option>

<option value="bean">Bean Paste Bun</option>

<option value="nest">Bird-Nest Bun</option>

</select>

<input type="submit" name="submit">

</form>

Selected buns:

<br/>

<?php

foreach ($_POST['lunch'] as $choice) {

    print "You want a $choice bun. <br/>";

}

?>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

foreach() wants an array as first parameter. If it gets something else it will produce the warning
Warning: Invalid argument supplied for foreach()
If your script is called without the post parameter lunch[] (e.g. when you enter the url in your browser's locationbar), there will be no $_POST['lunch'] ...and that's not an array ;)

Code: Select all

<html>
	<head>
		<title>form test</title>
	</head>
	<body>
		<pre><?php echo 'start: ', date('H:i:s'); ?></pre>
		<form method="POST" action="test.php">
			<div>
				<select name="lunch[]" multiple>
					<option value="pork">BBQ Pork Bun</option>
					<option value="chicken">Chicken Bun</option>
					<option value="lotus">Lotus Seed Bun</option>
					<option value="bean">Bean Paste Bun</option>
					<option value="nest">Bird-Nest Bun</option>
				</select>
				<input type="submit" name="submit">
			</div>
		</form>
		
		Selected buns:
		<br/>
<?php
if ( isset($_POST['lunch']) && is_array($_POST['lunch']) ) {
	foreach ($_POST['lunch'] as $choice) {
		print "You want a $choice bun. <br/>";
	}
}
?>
	</body>
</html>
ant_sutton
Forum Commoner
Posts: 32
Joined: Thu May 05, 2005 5:27 am

re

Post by ant_sutton »

Hi. thanks for your reply. works great!!

what an awful book if the examples are wrong:). the way its written in the book it should work the way I wrote it.

cheers

Anthony
Post Reply