Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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.

<?php
    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 form_data with these variables as its elements, so I inserted the following:

<?php
    $form_data = array();

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

    print_r($form_data);
?>

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 $number, 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.

like image 286
noidentity63 Avatar asked Jul 23 '14 03:07

noidentity63


People also ask

What is key in associative array in PHP?

Associative arrays are arrays that use named keys that you assign to them.

Can you put variables in an array PHP?

Yes, you can store variables within arrays, though you'll need to remove the space between $result and the opening bracket.

What is key in associative array?

An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.


2 Answers

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'));
like image 88
dave Avatar answered Oct 06 '22 01:10

dave


You can this with a loop. Create an array of variable names that you'll either white list (keep) or black list (remove) to help remove entries like submit from your array:

$blacklist = array('submit');

$form_data = array();
foreach($_POST as $key => $value) {
    if(in_array($key, $blacklist))
        continue; // skip unwanted entries

    $form_data[$key] = $value;
}

Apply any trim() or other formatting during your loop.

Likewise, if you wanted to whitelist the variables you want to keep you can use a similar process:

$whitelist = array('username', 'password', 'email', 'country');

foreach($whitelist as $key) {
    if(isset($_POST[$key]) && $_POST[$key] != '')
        $form_data[$key] = $_POST[$key];
}
like image 40
scrowler Avatar answered Oct 06 '22 00:10

scrowler