PHP best way to MD5 multi-dimensional array?

PHP best way to MD5 multi-dimensional array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Hashing Multi-dimensional Arrays in PHP: A Practical Guide

There is no native function in PHP that accepts a multi-dimensional array and returns a hash directly. The language provides md5(), sha1(), and hash() for single strings, but arrays must first be serialized. Attempting to pass an array straight into these functions will result in a fatal error or unexpected behavior depending on the specific function and PHP version.

The most robust approach involves serializing the array structure before hashing. The standard method is to use serialize() to convert the multi-dimensional array into a string representation, then apply the hash function to that string. This preserves the data types and structural hierarchy of the original array. For example, an integer key and a numeric key treated differently within the same level will serialize distinctly, ensuring the resulting hash reflects the exact structure.

$data = [
    'user' => ['id' => 1, 'name' => 'Alice'],
    'role' => 'admin'
];

$serialized = serialize($data);
$hash = md5($serialized);
echo $hash;

However, this approach introduces a significant security vulnerability if you are using MD5 for authentication or sensitive data verification. MD5 is cryptographically broken and vulnerable to collision attacks. If your goal is to store passwords or verify tokens, you must use password_hash() combined with password_verify(), not raw hashing of serialized data. Even for non-sensitive data like checksums or simple integrity checks, using a modern hash algorithm like SHA-256 (via hash('sha256', ...)) is strongly recommended over MD5 to prevent potential future analysis attacks.

If you need the hash to be consistent across different environments regardless of how serialize() orders internal structures (which can sometimes vary based on PHP version or specific extensions), you should consider a custom traversal function. While serialize() is generally deterministic in standard builds, relying on it for critical integrity checks without understanding the underlying serialization format can lead to subtle bugs if you switch PHP versions. A recursive loop that explicitly concatenates key-value pairs offers more control over the string generation process.

function arrayToString(array $array): string {
    $str = '';
    foreach ($array as $key => $value) {
        // Handle nested arrays recursively
        if (is_array($value)) {
            $str .= '(' . $key . ':' . arrayToString($value) . ')';
        } else {
            $str .= '[' . $key . ']' . '=' . var_export($value, true);
        }
    }
    return $str;
}

$hash = md5(arrayToString($data));

This custom implementation ensures that the hash string explicitly includes the keys in a predictable order. It avoids the potential ambiguity of serialize() where complex objects or specific data types might serialize differently depending on the PHP runtime environment. This is particularly important if you are generating hashes for external APIs or storing them in a database alongside user input.

When working with Laravel, you might find yourself needing to hash complex request payloads or cache keys derived from arrays. While Laravel does not provide a built-in "hash array" helper, the framework's extensive ecosystem offers tools to handle serialization and hashing securely. For instance, if you are building an API where the payload structure must remain immutable, hashing the serialized form is a common pattern for generating unique identifiers (like cache_key or request signatures).

Be mindful of the performance implications. Serializing large arrays adds overhead before the hash calculation begins. If you are processing thousands of requests per second, consider whether a full serialization is necessary or if a simpler JSON encoding (json_encode()) combined with a strong hash algorithm like SHA-256 would suffice for your specific use case. JSON is more human-readable and language-agnostic, whereas serialize() is PHP-specific.

Ultimately, the "best" way depends on your security requirements. For non-sensitive data integrity, hash('sha256', serialize($array)) provides a good balance of simplicity and robustness. For sensitive data, never use MD5 on serialized arrays; always utilize Laravel's built-in hashing functions or password-specific helpers designed for that purpose.

Our network