I'm confused as to exactly what this does and how do you use it in your form processing. Does it only remove unwanted $_POST entries that are not in $expected[]? Should I still use $_POST[ 'carModel'] to get the value? Or might there be a better way?
<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
if ( !empty( $_POST[ $key ] ) ) {
${$key} = $_POST[ $key ];
}
else
{
${$key} = NULL;
}
}
?>
Right, the pseudo-code ${$variable} is the creation of a new variable, aka:
//$_POST['test'],$_POST['future']
foreach( $_POST AS $key ) {
${$key} = $_POST[ $key ];
}
you are assign $_POST[$key] to $test, like $test = $_POST[$key]; echo $future; //have the same value of $_POST['future']
Now you can skip using $_POST to use $test, all array keys in post should be allocate in one variable called by the name of the key;
On your example, the $excepted work like a filter to only assign the variables that's in this array. You should user filters instead to sanitaze $_POST before assign to ${$}.
It creates variables $carModel, $year etc with content of the corresponding POST fields, or null if there's nothing.
<?php
// builds an array
$expected = array( 'carModel', 'year', 'bodyStyle' );
// loops over the array keys (carModel, year...)
foreach( $expected AS $key ) {
// checks, if this key is found in the incomming POST array and not empty
if ( !empty( $_POST[ $key ] ) ) {
// assigns the value of POST, to a variable under the key name
${$key} = $_POST[ $key ];
} else {
// or nulls it, which is totally pointless :)
${$key} = NULL;
}
}
?>
The intention with the $expected array is to provide a whitelist for the POST array keys. There are better ways for implementing this, especially filter_input(), filter_input_array().
Example Code http://www.php.net/manual/en/function.filter-input-array.php
if post data as in example
$_POST["carModel"] = "BMW";
$_POST["year"] = 2013;
It will means...
$carModel = "BMW";
$year = 2013;
$bodyStyle = null;
It is same as
extract( $_POST );