Tek
Tek

Reputation: 3050

Rewriting an if check into a function

http://localhostr.com/files/V1ruKKj/capture.png

I want to rewrite all these ifs to something more manageable for lots of form fields.

I know it's not right but I want to rewrite it to something like this:

$fields = array(); 

function infcheck($var) 
{ 
if ( !empty( $var ) ) 
{ 
$fields[$var] = $var; 
} 

} 

infcheck( $_POST['streetname'] ); 
infcheck( $_POST['city'] ); 
infcheck( $_POST['state'] );

Basically when I run infcheck() I want the output to look like this:

Assuming $_POST['streetname'] is "Circle Street"

streetname => "circle street"

for a full example:

$fields = array(); 

infcheck( $_POST['streetname'] ); 
infcheck( $_POST['city'] ); 

//would be:

$fields = array(streetname => 'Circle Street', city => 'New York City');

I guess what I'm having trouble with is keeping the name of the form when $_POST['formname'] is turned into a variable.

Upvotes: 0

Views: 80

Answers (2)

Christian
Christian

Reputation: 96

You could just put the array of values you want to pass through a foreach loop..

foreach($_POST as $key => $value){

$fields[$key] = $value;

}

Upvotes: 0

deceze
deceze

Reputation: 522042

What you're basically doing is this:

$fields = array_filter($_POST);

If you want to limit the $fields array to certain keys in a predetermined list and skip anything in the $_POST array that's not on that list, you can do something like this:

$whitelist = array('streetname', 'city', ...);
$fields = array_filter(array_intersect_key($_POST, array_flip($whitelist)));

Upvotes: 2

Related Questions