<?php
/**
* Compares values from two web forms for an experiment.
*
* @param array $form1 Data from the first form.
* @param array $form2 Data from the second form.
* @return array An associative array containing the comparison results.
*/
function compareForms(array $form1, array $form2): array
{
$results = [];
// Check if the forms have the same keys (same fields)
if (array_keys($form1) !== array_keys($form2)) {
$results['error'] = 'Forms have different fields.';
return $results; // Exit if fields are different
}
foreach ($form1 as $field => $value1) {
if (isset($form2[$field])) {
$value2 = $form2[$field];
// Compare values based on data type
if (is_numeric($value1) && is_numeric($value2)) {
$comparison = compareNumbers($value1, $value2);
} elseif (is_string($value1) && is_string($value2)) {
$comparison = compareStrings($value1, $value2);
} else {
$comparison = $value1 === $value2; // For other types, use strict comparison
}
$results[$field] = [
'value1' => $value1,
'value2' => $value2,
'match' => $comparison,
];
} else {
$results[$field] = [
'value1' => $value1,
'value2' => null,
'match' => false, // Field missing in form2
];
}
}
return $results;
}
/**
* Compares two numbers.
*
* @param float $num1 The first number.
* @param float $num2 The second number.
* @return int 0 if equal, 1 if num1 > num2, -1 if num1 < num2.
*/
function compareNumbers(float $num1, float $num2): int
{
if ($num1 == $num2) {
return 0;
} elseif ($num1 > $num2) {
return 1;
} else {
return -1;
}
}
/**
* Compares two strings.
*
* @param string $str1 The first string.
* @param string $str2 The second string.
* @return int 0 if equal, 1 if str1 > str2, -1 if str1 < str2.
*/
function compareStrings(string $str1, string $str2): int
{
$comparison = strcmp($str1, $str2); // Use strcmp for string comparison
if ($comparison == 0) {
return 0;
} elseif ($comparison > 0) {
return 1;
} else {
return -1;
}
}
// Example Usage (replace with your actual form data)
$form1Data = [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York',
'score' => 85.5,
];
$form2Data = [
'name' => 'John Doe',
'age' => 30,
'city' => 'London',
'score' => 92.0,
];
$comparisonResults = compareForms($form1Data, $form2Data);
// Output the results (you can format this as needed)
echo "<pre>";
print_r($comparisonResults);
echo "</pre>";
?>
Add your comment