1. <?php
  2. /**
  3. * Batch timestamp operations.
  4. *
  5. * @param array $timestamps An array of timestamps (integers or floats).
  6. * @param string $operation The operation to perform ('add', 'subtract', 'multiply', 'divide').
  7. * @param mixed $value The value to use for the operation.
  8. * @return array An array of the results, or an error message.
  9. */
  10. function batchTimestamps(array $timestamps, string $operation, $value): array
  11. {
  12. $results = [];
  13. foreach ($timestamps as $timestamp) {
  14. switch ($operation) {
  15. case 'add':
  16. $results[] = $timestamp + $value;
  17. break;
  18. case 'subtract':
  19. $results[] = $timestamp - $value;
  20. break;
  21. case 'multiply':
  22. $results[] = $timestamp * $value;
  23. break;
  24. case 'divide':
  25. if ($value === 0) {
  26. return ['error' => 'Division by zero'];
  27. }
  28. $results[] = $timestamp / $value;
  29. break;
  30. default:
  31. return ['error' => 'Invalid operation'];
  32. }
  33. }
  34. return $results;
  35. }
  36. // Example usage:
  37. $timestamps = [1678886400, 1678972800, 1679059200]; // Example timestamps (Unix timestamps)
  38. // Add 10 seconds to each timestamp
  39. $results = batchTimestamps($timestamps, 'add', 10);
  40. print_r($results);
  41. // Subtract 5 seconds
  42. $results = batchTimestamps($timestamps, 'subtract', 5);
  43. print_r($results);
  44. // Multiply by 2
  45. $results = batchTimestamps($timestamps, 'multiply', 2);
  46. print_r($results);
  47. // Divide by 2
  48. $results = batchTimestamps($timestamps, 'divide', 2);
  49. print_r($results);
  50. //Division by zero
  51. $results = batchTimestamps($timestamps, 'divide', 0);
  52. print_r($results);
  53. ?>

Add your comment