1

I would like to give incrementing variable name to each post value and take the assigned variable and build array. The below is what I tried

$list = array();
$x = 0;
$prefix = '$var_';

foreach(array_slice($_POST, 1) as $test){
   $x++;
   $list[] = "{$prefix}{$x} = {$test};":
}

echo implode("  ", $list);

So if I had 4 values in the post, like 0, a, b, c it would echo something like

$var_1 = a;  $var_2 = b;  $var_3 = c;

I would like to put all the three $vars in array like below and use their value. This is where I am stuck. Any help?

$vars = array($var_1, $var_2, $var_3)

What I'm trying to achieve is to insert dynamic data to table where I only know the table_name,

 $stmt = $mydb->prepare($sql);//I am able to populate the $sql and $str
 $stmt->bind_param($str, $vars);
 $stmt->execute();
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
user2666310
  • 103
  • 2
  • 15
  • 4
    I would bet you dont really want to do that. Please explain what you are trying to achieve. There is almost definitely a better way of doing it. – RiggsFolly Sep 28 '14 at 18:07

3 Answers3

1

I believe you're looking for the extract() function:

$list = array();
$prefix = 'var_';
$_POST = array("TEST",1,2,3,"XYZ"); // post example

$x = 0;
foreach(array_slice($_POST, 0) as $test) {
    $x++;
    $list[$prefix.$x] = "{$test}";
}
extract($list);
echo $var_1; // outputs TEST

// print_r($list);

/*
Array
(
    [var_1] => TEST
    [var_2] => 1
    [var_3] => 2
    [var_4] => 3
    [var_5] => XYZ
)
*/

*Extreme caution should be exercised when using functions with $_POST, $_GET, $_FILES, etc.

l'L'l
  • 44,951
  • 10
  • 95
  • 146
0

A bad and dirty way of doing it (no security)

$list = implode("  ", $list);
eval($list)

Now, you have $var_1, $var_2 defined. :)

Beware, eval is dangerous, dont use it.

Yash Sodha
  • 713
  • 3
  • 13
0

You can achieve the first part with list: as this example PHP Assign array to variables

You could skip all of that and do something like this:

$vars = $_POST

and use the array as-is (ovbiously you will need to sanitise your data before doing this.

or you could pick from these methods: Fastest way to add prefix to array keys?

You can also post an array from a form (if its a form thats populating your POST) see the answer to this post Posting array from form

Then you could do:

$vars = $_POST['data_array_name'];

(and sanitise it too)

Community
  • 1
  • 1
Jonathan
  • 1,542
  • 3
  • 16
  • 24