Reputation: 337
I have a selection of post fields which are submitted through a web form:
$_POST['first_name'];
$_POST['last_name'];
$_POST['house_number'];
$_POST['postcode'];
etc
I would like to add the following code structure to each one:
if (isset($_POST['first_name'])) {
$first_name = mysql_prep($_POST['first_name']);
}
How can I use a loop to achieve this to save having to repeat myself multiple times?
Thanks
Upvotes: 0
Views: 1268
Reputation: 18550
how about
foreach ($_POST as $key => $value){
$$key = mysql_prep($value);
}
$$ is setting a variable variable
Upvotes: 1
Reputation: 32148
Try using foreach:
foreach( $_POST as $key => $value ) {
$$key = mysql_prep( $value );
}
Upvotes: 2
Reputation: 10686
Use array_map() PHP function for apply some operations for all array elements.
And after that extract($_POST)
if you want to receive variables with names like $_POST
array keys.
Upvotes: 2
Reputation: 38416
You can use PHP's extract()
function to do this for you.
extract($_POST);
// you now have a variable for every key in $_POST
If you only want a certain list of keys, and not the full array, you can also use variable-variables
(a variable with two leading $
, such as $$var
):
$keysToExtract = array('first_name', 'last_name');
foreach ($keysToExtract as $key) {
$$key = $_POST[$key];
}
// you now have $first_name and $last_name
Upvotes: 8