1. <?php
  2. /**
  3. * Compares values from two web forms for an experiment.
  4. *
  5. * @param array $form1 Data from the first form.
  6. * @param array $form2 Data from the second form.
  7. * @return array An associative array containing the comparison results.
  8. */
  9. function compareForms(array $form1, array $form2): array
  10. {
  11. $results = [];
  12. // Check if the forms have the same keys (same fields)
  13. if (array_keys($form1) !== array_keys($form2)) {
  14. $results['error'] = 'Forms have different fields.';
  15. return $results; // Exit if fields are different
  16. }
  17. foreach ($form1 as $field => $value1) {
  18. if (isset($form2[$field])) {
  19. $value2 = $form2[$field];
  20. // Compare values based on data type
  21. if (is_numeric($value1) && is_numeric($value2)) {
  22. $comparison = compareNumbers($value1, $value2);
  23. } elseif (is_string($value1) && is_string($value2)) {
  24. $comparison = compareStrings($value1, $value2);
  25. } else {
  26. $comparison = $value1 === $value2; // For other types, use strict comparison
  27. }
  28. $results[$field] = [
  29. 'value1' => $value1,
  30. 'value2' => $value2,
  31. 'match' => $comparison,
  32. ];
  33. } else {
  34. $results[$field] = [
  35. 'value1' => $value1,
  36. 'value2' => null,
  37. 'match' => false, // Field missing in form2
  38. ];
  39. }
  40. }
  41. return $results;
  42. }
  43. /**
  44. * Compares two numbers.
  45. *
  46. * @param float $num1 The first number.
  47. * @param float $num2 The second number.
  48. * @return int 0 if equal, 1 if num1 > num2, -1 if num1 < num2.
  49. */
  50. function compareNumbers(float $num1, float $num2): int
  51. {
  52. if ($num1 == $num2) {
  53. return 0;
  54. } elseif ($num1 > $num2) {
  55. return 1;
  56. } else {
  57. return -1;
  58. }
  59. }
  60. /**
  61. * Compares two strings.
  62. *
  63. * @param string $str1 The first string.
  64. * @param string $str2 The second string.
  65. * @return int 0 if equal, 1 if str1 > str2, -1 if str1 < str2.
  66. */
  67. function compareStrings(string $str1, string $str2): int
  68. {
  69. $comparison = strcmp($str1, $str2); // Use strcmp for string comparison
  70. if ($comparison == 0) {
  71. return 0;
  72. } elseif ($comparison > 0) {
  73. return 1;
  74. } else {
  75. return -1;
  76. }
  77. }
  78. // Example Usage (replace with your actual form data)
  79. $form1Data = [
  80. 'name' => 'John Doe',
  81. 'age' => 30,
  82. 'city' => 'New York',
  83. 'score' => 85.5,
  84. ];
  85. $form2Data = [
  86. 'name' => 'John Doe',
  87. 'age' => 30,
  88. 'city' => 'London',
  89. 'score' => 92.0,
  90. ];
  91. $comparisonResults = compareForms($form1Data, $form2Data);
  92. // Output the results (you can format this as needed)
  93. echo "<pre>";
  94. print_r($comparisonResults);
  95. echo "</pre>";
  96. ?>

Add your comment