How can arrays in PHP be utilized to simplify the process of checking for changes in form data?
When dealing with form data in PHP, it can be cumbersome to manually check each form field for changes compared to the original data. One way to simplify this process is by utilizing arrays to store the original form data and then comparing it to the submitted form data. This allows for a more efficient way to check for changes in form data and take appropriate actions based on those changes.
// Store original form data in an array
$originalFormData = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'phone' => '1234567890'
];
// Get submitted form data
$submittedFormData = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone']
];
// Compare original data with submitted data
$changes = [];
foreach ($originalFormData as $key => $value) {
if ($originalFormData[$key] != $submittedFormData[$key]) {
$changes[$key] = $submittedFormData[$key];
}
}
// Output changes
if (!empty($changes)) {
echo 'Changes detected:';
foreach ($changes as $key => $value) {
echo $key . ': ' . $value . '<br>';
}
} else {
echo 'No changes detected.';
}