In PHP, how do I cache arrays in vanilla PHP?

Caching arrays in vanilla PHP can significantly improve the performance of your application, particularly when you are dealing with large datasets or expensive computations. Below is an example of how to cache an array using PHP.

<?php // Function to cache array data function cacheArray($key, $data, $cacheTime = 3600) { $cacheFile = __DIR__ . "/cache/{$key}.cache"; // Check if cache file exists and is still valid if (file_exists($cacheFile) && (filemtime($cacheFile) > (time() - $cacheTime))) { // Retrieve data from the cache return unserialize(file_get_contents($cacheFile)); } else { // No valid cache, compute data $computedData = $data(); // Assuming $data is a callable that returns an array // Store new data in cache file_put_contents($cacheFile, serialize($computedData)); return $computedData; } } // Example usage $arrayData = cacheArray('myArray', function() { // Simulating a heavy data computation return range(1, 100); // Example data }); print_r($arrayData); // Display cached data ?>

caching php arrays performance optimization cache files