0

I have a variable like:

foreach ($array as $data){
    $namee=$data['Label_Field'];
    ${$namee} = $_POST[$namee];
}

How do I get a value like ("data", "data") using those variables?

u_mulder
  • 54,101
  • 5
  • 48
  • 64

2 Answers2

1

you can use $$ in php

Example:

$a = 'name';
$$a = 'test';
echo $name;

Result:

test

Example of your code:

foreach ($array as $data){
    $namee = $data['Label_Field'];
    $$namee = $_POST[$namee];
}

I also suggest you read the following:

https://www.php.net/manual/en/language.variables.variable.php

https://www.geeksforgeeks.org/php-vs-operator/

https://www.javatpoint.com/php-dollar-doubledollar

what is "$$" in PHP

Erfan Bahramali
  • 392
  • 3
  • 13
0

Avoid using variable variables, simply filter $_POST into a new variable, else there is a likely risk of overwriting important variables ($db_connection?).

Instead do some thing like:

<?php
$_POST['foo'] = '';
$_POST['bar'] = '';
$_POST['baz'] = '';

// fields
$fields = [['Label_Field' => 'foo']];

// just labels
$labels = array_column($fields, 'Label_Field');

// filter $_POST by keys which are in $labels
$data = array_filter($_POST, fn($k) => in_array($k, $labels), ARRAY_FILTER_USE_KEY);

print_r($data);

Then use $data['foo'] instead of $foo.

View online: https://3v4l.org/vna02

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106