wir
8/20/2015 - 3:15 PM

PHP: howto automatically create variables with the same name as key in POST array

PHP: howto automatically create variables with the same name as key in POST array

// One more cautios way of extracting all input fields at once is:
extract( $_POST, EXTR_OVERWRITE, "form_" );
// This way all your input variables will be called $form_foo and $form_bar at least.
// Avoid doing that in the global scope - not because global is evil, but because nobody ever cleans up there.
// http://goo.gl/3Q5RV
// Thanks to Sergej Müller @wpSEO

// you know this how you are doing:
$username=$_POST["username"];
$age=$_POST["age"];
$age2=$_POST["age2"];
$age3=$_POST["age3"];
// etc.

// This is how to initialize the whole Array
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}


// Thanks to http://www.catswhocode.com/blog/10-awesome-php-functions-and-snippets