Hi guys,
Quote:
quote:Originally posted by quesadilla5
Don't forget that you're creating a multidimensional array...
$_POST['names'] becomes an array itself. Also foreach is a control structure, its purpose is to loop, in javascript you'd use for/in (not an exact equivalent but the closest).. but you still have to create the statement as a control structure, or it doesn't do anything useful.
foreach($_POST['names'] as $name)
{
echo $name;
}
The syntax is:
foreach ($array as $key => $value) ...
|
Well, the fact that $_POST['names'] is an array is why you can use it in a foreach loop in the first place. The only difference between this:
foreach($_POST['names'] as $name)
and this:
foreach($_POST['names'] as $key => $val)
is that the 2nd approach allows you to also get the key of each element in the array, should you need it.
Since the HTML form doesn't explicitly SET the array keys (they're numeric keys created on the fly via the empty bracket notation, i.e. "names[]"), you don't necessarily NEED the actual key value, so omitting it from the foreach() loop is okay.
In fact, it's a wise decision because you don't introduce the overhead of creating a variable to store a value that you won't end up using.
All that being said, there should really be no reason why your code doesn't work -- that is, it works for me when I use this simple test script (basically a copy/paste of your original code with only slight modifications and a lot of beautification/reformatting):
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="1">
<tr>
<th> This is the HEADER</th>
</tr>
<tr>
<td>
<select name="names[]" multiple size="5">
<option value="Tammy Jones">Tammy Jones</option>
<option value="Tommy Jones">Tommy Jones</option>
<option value="Fred Flintstone">Fred Flintstone</option>
<option value="Heather Locklear">Heather Locklear</option>
</select>
</td>
</tr>
<tr>
<td align=center>
<input type="submit" value="Submit" >
</td>
</tr>
</table>
</form>
<pre>
<?php
if (isset($_POST['names']))
{
foreach($_POST['names'] as $name)
{
echo "Name is $name\n";
}
}
?>
Also, notice how much easier proper indentation and formatting makes it to verify that all your HTML tags are properly nested -- that is, your tags don't overlap boundaries.
In your original code, you started the <select> tag in one table cell, and closed it in a completely separate row. That's really really really bad style, and should be avoided at all costs.
Take care,
Nik
http://www.bigaction.org/