How can a "WhiteList" approach be implemented to improve the validation of form fields in PHP?

To implement a "WhiteList" approach for form field validation in PHP, we can define an array of allowed values for each field and check if the submitted value is in the whitelist. This helps prevent unexpected or malicious input from being processed.

// Define a whitelist of allowed values for each form field
$whitelist = [
    'username' => ['john', 'jane', 'admin'],
    'email' => ['example@example.com', 'test@test.com'],
    'age' => [18, 21, 25, 30]
];

// Validate form fields against the whitelist
foreach ($_POST as $field => $value) {
    if (!in_array($value, $whitelist[$field])) {
        // Invalid input, handle accordingly (e.g. display an error message)
        echo "Invalid input for field: $field";
    }
}