0

i have this long form that requires multiple inputs, how can i properly insert these inputs into an array using a foreach loop?

assuming i have these:

$name = $_POST['name'];
$color = $_POST['color'];
$age= $_POST['age'];
$gender = $_POST['gender'];
$location = $_POST['location'];
...etc..

instead of typing such this..

$myarray = array('id'=>$id,'name'=>$name,'color'=>$color,'age'=>$age,'gender'=>$gender,'location'=>$location,etc...);

how can i let foreach loop insert the appropriate values into the array?

bobbyjones
  • 2,029
  • 9
  • 28
  • 47

3 Answers3

2
$myarray = $_POST;

This is enough. $_POST is already an array as Suresh Kamrushi stated.

0
$myarray = array();
foreach ($_POST as $post){
$myarray[] = $post;
}

Edit As correctly pointed out in the comments below, $myarray = array_values($_POST); works too.

ggdx
  • 3,024
  • 4
  • 32
  • 48
  • 1
    The question is not very clear. But your `foreach` loop is useless. You can simply do `$myarray = array_values($_POST);` instead. – Amal Murali Nov 06 '13 at 14:16
  • This is a useless `foreach` loop – David Nov 06 '13 at 14:16
  • @AmalMurali - Yep, that would do too. David, it's what the OP apparently asks for even though no abundance of info given in the question. – ggdx Nov 06 '13 at 14:19
0

all you need is this

$myarray = array();
foreach ($_POST as $key => $value){
   $myarray[$key] = $value;
}
Developerium
  • 7,155
  • 5
  • 36
  • 56