odedta
odedta

Reputation: 2478

PHP Optimization: Form Variables

Lets say I have a form with 30 fields. I was trying to think of a way to optimize a solution to check on the server side if all these fields are empty or contain a specific value and the them accordingly.

So, the code for 1 variable would be as follows:

if((!isset($_POST['usa_state_list'])) || (strcmp($_POST['usa_state_list'],'undefined') == 0)) {
    $usa_state_list = '';
}
else {
    $usa_state_list = $_POST['usa_state_list'];
}

Now imagine 30 of these fields, you'd have to have 30 of those if statements. Do you have an idea on how to optimize this? switch or for loop perhaps? NOTE: Let's stick to this example where I check if the field is either empty or contain the undefined string.

Thanks

Upvotes: 0

Views: 63

Answers (2)

Álvaro González
Álvaro González

Reputation: 146558

Built-in filter functions are only slightly verbose:

$usa_state_list = filter_form(INPUT_POST, 'usa_state_list');

... but since you need to do some custom post-processing and you need to output individual variables I think it's better to simply write your own:

function post($name) {
    $value = filter_input(INPUT_POST, $name);
    if ($value!=='undefined') {
        return $value;
    } else {
        return '';
    }
}
$usa_state_list = post('usa_state_list');

Of course, if you think that code legibility is for wimps then the sky is the limit:

foreach (
    [
        'usa_state_list',
        'foo',
        'bar',
    ] as $name
) {
    $$name = post($name);
}

Upvotes: 1

timgavin
timgavin

Reputation: 5166

Just create a function and use it over and over. Simple example I just whipped up (hasn't been tested):

function checkPost($key) {

    // check if the element has been posted
    if(isset($_POST[$key])) {

        // check if element is empty
        if($_POST[$key] != '') {

            // check if the element contains a specific value
            if($_POST[$key] == 'my specific value') {

                // do whatever here...

            } else {

                // return the posted value
                return strip_tags($_POST[$key]);
            }

        } else {

            // POST value was empty
            // you could return an error message here...
            // or add to a global $errors array...
            return $key . ' is required';
        }
    }

    // the element has not been posted
    return false;
}

$usa_state_list = checkPost('usa_state_list');
$name = checkPost('name');
$address = checkPost('address');

Upvotes: 1

Related Questions