Avatar ·

Serialization of PHP arrays: json_encode vs serialize — which to choose?

Hello everyone! I'm a beginner in PHP and faced a dilemma while developing a project. I need to save arrays to cache (files or Redis) and then read them back. I found two methods: serialize() and json_encode(). But I can't figure out which one is better to use. Here's an example of my code: ```php // Option 1: serialize $data = ['user' => 'Ivan', 'age' => 30, 'hobbies' => ['reading', 'programming']]; $serialized = serialize($data); file_put_contents('cache.txt', $serialized); $restored = unserialize(file_get_contents('cache.txt')); // Option 2: json_encode $json = json_encode($data, JSON_UNESCAPED_UNICODE); file_put_contents('cache.json', $json); $decoded = json_decode(file_get_contents('cache.json'), true); ``` Both options seem to work, but I noticed some oddities: 1. serialize() creates a more "messy" string with some letters and numbers. 2. json_encode() produces clean JSON that can be opened in any editor. 3. When working with Russian characters, json_en