1. <?php
  2. /**
  3. * Hashes array values for routine automation with basic input validation.
  4. *
  5. * @param array $data The array of values to hash.
  6. * @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
  7. * @return array An array containing the original values and their corresponding hashes, or an error message if validation fails.
  8. */
  9. function hashArrayValues(array $data, string $hash_algorithm = 'sha256'): array
  10. {
  11. // Input validation: Check if the input is an array
  12. if (!is_array($data)) {
  13. return ['error' => 'Invalid input: Input must be an array.'];
  14. }
  15. // Input validation: Check if the hashing algorithm is supported
  16. $supported_algorithms = ['sha256', 'md5', 'sha1']; //Add more as needed
  17. if (!in_array($hash_algorithm, $supported_algorithms)) {
  18. return ['error' => 'Invalid hashing algorithm. Supported algorithms: ' . implode(', ', $supported_algorithms)];
  19. }
  20. $hashed_data = [];
  21. foreach ($data as $value) {
  22. //Input validation: Check if the value is a string
  23. if (!is_string($value)) {
  24. return ['error' => 'Invalid input: All values in the array must be strings.'];
  25. }
  26. $hash = hash($hash_algorithm, $value); // Hash the value using the specified algorithm
  27. $hashed_data[$value] = $hash; // Store the original value and its hash
  28. }
  29. return $hashed_data;
  30. }
  31. //Example Usage
  32. // $my_array = ['value1', 'value2', 'value3'];
  33. // $hashed_array = hashArrayValues($my_array, 'sha256');
  34. // print_r($hashed_array);
  35. ?>

Add your comment