Automatically creates variables with the same name as the key in the POST array

This snippet is very helpful for every POST processing. All you need is an array with expected keys in the POST array. This snippet automatically creates variables with the same name as the key in the POST array. If the key is not found in the POST array the variable is set to NULL. Basically you dont need to write:

$username=$_POST["username"];
$age=$_POST["age"];
etc.

This snippet will do this boring part of every PHP code with POST handling so you can fully focus on a validation of the input, because that is much more important.


<?php
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}
?>
Enjoyed this article? Please consider donating: 3FVR5qaxYV8yAgNUUS7FC3o8c54YfDR5zK