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'];
Keywords
Related Questions
- What alternative methods, such as PDO, can be used instead of mysql_* functions for database connectivity in PHP?
- What potential issues can arise when trying to separate and combine numbers from a string in PHP?
- How can PHP variables be effectively used in conjunction with file creation tasks to ensure proper naming and handling of text files?