How can serialization and unserialization be used to store and retrieve arrays from a file in PHP?
To store and retrieve arrays from a file in PHP, you can use serialization and unserialization. Serialization converts an array into a string that can be easily stored in a file, while unserialization converts the stored string back into an array. This allows you to save and retrieve complex data structures like arrays without losing their structure or content.
// Store an array in a file using serialization
$data = ['apple', 'banana', 'cherry'];
file_put_contents('data.txt', serialize($data));
// Retrieve the array from the file using unserialization
$stored_data = file_get_contents('data.txt');
$retrieved_data = unserialize($stored_data);
print_r($retrieved_data); // Output: Array ( [0] => apple [1] => banana [2] => cherry )