noidentity63 noidentity63 - 1 year ago 83
PHP Question

PHP - Adding variables to an associative array with the variable names as keys

This is my first post so I'm sorry for any mistakes that I may not be aware of.

I've been fidddling with forms and POST for the past days now and I have a curious question on a certain situation.

I have this code in my basic web form. I declared some variables as shown below.

if (isset($_POST['submit'])) {
// Form submitted
$username = isset($_POST['username'])? $_POST['username'] : "";
$password = isset($_POST['password'])? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$country = isset($_POST['country']) ? $_POST['country'] : "";

I wanted to create an array
with these variables as its elements, so I inserted the following:

$form_data = array();

$form_data['username'] = $username;
$form_data['password'] = $password;
$form_data['email'] = $email;
$form_data['country'] = $country;


My question is that is there any method in PHP that I don't know of in where I can get the same result? The variable name will be assigned as a key in the array and I prefer not to type in the keys' names manually like on that bit of code above.

So in short, if I have a variable named
, I want to add its value into an array with 'number'(the variable name) as its key. Is there a method that does this automatically?

I hope I've made this question clear enough.

Answer Source

You could use compact:

$form_data = compact('username', 'password', 'email', 'country');

As long as you have the variables $username, $password, $email, and $country it will create the array you described.

compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key.

Or, you could do a whitelist approach:

function array_whitelist($array, $whitelist = array()) {
    return array_merge(array_flip($whitelist), 
                       array_intersect_key($array, array_flip($whitelist)));

$form_data = array_whitelist($_POST, array('username', 'password', 'email', 'country'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download