Jump to content

Invalid argument supplied for foreach


JPark

Recommended Posts

Warning: Noob Alert...

 

I am playing around with forms and functions and am getting an error.

 

Here's the form:

<form action="functions.php" method="post" >
<p>Pick one or more colors:</p>
<p><input name="colors[]" type="checkbox" value="red"> Red  |  
        <input name="colors[]" type="checkbox" value="orange"> Orange  |  
        <input name="colors[]" type="checkbox" value="yellow"> Yellow  |  
        <input name="colors[]" type="checkbox" value="green"> Green  |  
        <input name="colors[]" type="checkbox" value="blue"> Blue  |  
        <input name="colors[]" type="checkbox" value="indigo"> Indigo  |  
        <input name="colors[]" type="checkbox" value="violet"> Violet</p>
          <hr align="left" width="560">
<p><input type="reset" name="Reset" value="Clear">  
<input type="submit" name="Submit" value="Submit"></p>
</form>

 

and here's the php results page:

<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"> 
  <tr> 
    <td colspan='2' style='background: #E5E5E5; padding:3px 10px;'> 
<p style='font-weight:bold; text-align:center;'>You
        are almost done...</p></td> 

  <tr> 
    <td colspan='2' style='background: #E5E5E5; border-bottom: 1px solid #000; padding:3px 10px;'> 
<input type="submit" value="ENTER" /></td> 
  </tr> 
  </table> 
</form> 
<?php
echo "<hr width='200px' align='left'>";
echo "<h4>My Function:</h4>";

$colors = $_POST['colors'];

function showColors(&$colors) {
foreach ($colors as $key => $value)
	{
		echo $key." ==> ".$value."    ";
	}
}

showColors($colors);
?> 

 

The first time I get the results page, I get my selected colors displayed no problem.  However, if I click Enter on the results page, I get

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\functions.php on line 87

 

What am I doing wrong?

 

Thanks!

 

Joe

Link to comment
https://forums.phpfreaks.com/topic/190874-invalid-argument-supplied-for-foreach/
Share on other sites

The second time you are hitting enter the $_POST array doesn't even exist, you are just refreshing the page.

 

put both pages you have on one single page and put a condition if the form is submitted or not and that will let you hit enter as much as you want!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.