What are some best practices for efficiently reading form data in PHP without repetitive code?

When reading form data in PHP, it is common to use the $_POST or $_GET superglobals to access the submitted data. To avoid repetitive code when reading multiple form inputs, you can create a function that loops through an array of input names and retrieves their values. This can help streamline the process and make your code more efficient.

function getFormData($inputs) {
    $data = [];
    
    foreach($inputs as $input) {
        if(isset($_POST[$input])) {
            $data[$input] = $_POST[$input];
        } else {
            $data[$input] = null;
        }
    }
    
    return $data;
}

// Usage example
$inputs = ['name', 'email', 'message'];
$formData = getFormData($inputs);

$name = $formData['name'];
$email = $formData['email'];
$message = $formData['message'];