Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I am getting " Invalid argument supplied for foreach()"?

Tags:

php

I have two pages in php the first contain a form which is:

<form method="post" action="addnames.php">
   <input type="text" name="name" placeholder="Name" /><br />
   <input type="text" name="name" placeholder="Name" /><br />
   <input type="text" name="name" placeholder="Name" /><br />
   <input type="text" name="name" placeholder="Name" /><br />

   <input type="submit" value="Done" />
</form>

this takes the data to other php page where I am using foreach to read the request in this way:

 foreach($_REQUEST['name'] as $name){ 
     //MY CODE
 }

So what is the problem?

like image 389
Hassan Avatar asked Feb 07 '23 21:02

Hassan


2 Answers

If you want to get name as an array then you need to change your form code:

<form method="post" action="addnames.php">
   <input type="text" name="name[]" placeholder="Name" /><br />
   <input type="text" name="name[]" placeholder="Name" /><br />
   <input type="text" name="name[]" placeholder="Name" /><br />
   <input type="text" name="name[]" placeholder="Name" /><br />

   <input type="submit" value="Done" />
</form>

Now you can get all names in your post request.

like image 62
hardik solanki Avatar answered Feb 10 '23 10:02

hardik solanki


Because only one name is sent to the server, and it's a string then not an array. To send an array of names, change your input name to name="name[]" to identify it as an array

<input type="text" name="name[]" placeholder="Name" />
...
like image 28
Coloured Panda Avatar answered Feb 10 '23 10:02

Coloured Panda