<?php
/**
* Hashes array values for routine automation with basic input validation.
*
* @param array $data The array of values to hash.
* @param string $hash_algorithm The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
* @return array An array containing the original values and their corresponding hashes, or an error message if validation fails.
*/
function hashArrayValues(array $data, string $hash_algorithm = 'sha256'): array
{
// Input validation: Check if the input is an array
if (!is_array($data)) {
return ['error' => 'Invalid input: Input must be an array.'];
}
// Input validation: Check if the hashing algorithm is supported
$supported_algorithms = ['sha256', 'md5', 'sha1']; //Add more as needed
if (!in_array($hash_algorithm, $supported_algorithms)) {
return ['error' => 'Invalid hashing algorithm. Supported algorithms: ' . implode(', ', $supported_algorithms)];
}
$hashed_data = [];
foreach ($data as $value) {
//Input validation: Check if the value is a string
if (!is_string($value)) {
return ['error' => 'Invalid input: All values in the array must be strings.'];
}
$hash = hash($hash_algorithm, $value); // Hash the value using the specified algorithm
$hashed_data[$value] = $hash; // Store the original value and its hash
}
return $hashed_data;
}
//Example Usage
// $my_array = ['value1', 'value2', 'value3'];
// $hashed_array = hashArrayValues($my_array, 'sha256');
// print_r($hashed_array);
?>
Add your comment