In PHP, how do I cache arrays with PHP 8+ features?

Learn how to effectively cache arrays in PHP using the features introduced in PHP 8 and above. This helps in improving performance by reducing computation times for frequently used data.
caching, PHP 8, performance optimization, arrays, data handling

 'John Doe',
    'email' => 'john@example.com',
    'age' => 30,
];

// Function to cache the array
function cacheArray(array $data): string {
    // Serialize the array and cache it
    $cacheFile = 'cache/data.cache';
    if (!file_exists($cacheFile) || filemtime($cacheFile) < time() - 3600) { // Cache for 1 hour
        file_put_contents($cacheFile, serialize($data));
    }
    
    return 'Data cached successfully!';
}

// Call the caching function
echo cacheArray($data);

// Function to retrieve the cached array
function getCachedArray(): ?array {
    $cacheFile = 'cache/data.cache';
    if (file_exists($cacheFile)) {
        return unserialize(file_get_contents($cacheFile));
    }
    
    return null;
}

// Retrieve and print the cached data
$cachedData = getCachedArray();
if ($cachedData !== null) {
    print_r($cachedData);
} else {
    echo 'No cached data found.';
}
?>
    

caching PHP 8 performance optimization arrays data handling