0

Given,

$required_fields = array('name', 'location', 'email');                               
foreach ($required_fields as $fieldname) {
    if (isset($_POST[$fieldname]) || !empty($_POST[$fieldname])) {      


        }

Now in the if statement, I need something like

$fieldname = $_POST[$fieldname]; 

So that i get

$name = "name", $location = "location" and $email = "email"

I tried $fieldname = $_POST[$fieldname] But it don't work. How can I do this dynamically?

1
  • When you think you need variable variables, it is time to step away from the keyboard and have a rethink. Sanitize user submission data using whitelisted keys: Yes. Variable variables: No. Commented Oct 5, 2024 at 6:40

4 Answers 4

9

You do it like this,

$$fieldname = $_POST[$fieldname]; 

This $$ notation is called variable variable.

Sign up to request clarification or add additional context in comments.

Comments

3

you could use extract function for this. To filter array you can use array_diff function

3 Comments

could be also useful to take a look to - Is using extract($_POST) insecure?
there's a possibility that extract() will overwrite your existing variables with new ones and that's debugging hell
@ianace Assigning variables like in question is a debugging hell.
1
$required_fields = array('name', 'location', 'email');
extract(array_intersect_keys($_POST, array_flip($required_fields)));

This will create local variables for each of the variables named in $required_fields only if it exists in the $_POST array. Otherwise, the variable will be undefined.

array_flip
array_intersect_key
extract

Comments

-2

You can also use

eval("$".$fieldname."='".$_POST["fieldname"]."';");

2 Comments

why invoke a new PHP interpreter?
This is another example of how the issue can be solved. Although is also dangerous if the values aren't validated properly. The final result is same as your given solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.