This is one of those questions where I must implore the OP to rethink their process. It only complicates your code to introduce associative keys that do not instantly synchronize with your form field names. This is the best advice that I can give you: declare a whitelist of keys and assign default values to each, then filter, then replace.
Since your values are all null
, your code can be made more DRY by calling array_fill_keys()
.
The following can be written as one line of code, but to show each step, I've printed the arrays to screen after each function call.
Code: (Demo)
$defaults = array_fill_keys(['first_name', 'last_name', 'years'], null);
var_export($defaults);
$_GET = [
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5
];
var_export($_GET);
$screened = array_intersect_key($_GET, $defaults);
var_export($screened);
$replaced = array_replace($defaults, $screened);
var_export($replaced);
Output:
array (
'first_name' => NULL,
'last_name' => NULL,
'years' => NULL,
)array (
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5,
)array (
'last_name' => 'doe',
'years' => 5,
)array (
'first_name' => NULL,
'last_name' => 'doe',
'years' => 5,
)
...p.s. makes sure that you use prepared statements with placeholders if you are sending any of the values to the database.