Store an array as JSON or as a PHP serialized array?

Technology CommunityCategory: PHPStore an array as JSON or as a PHP serialized array?
VietMX Staff asked 3 years ago
Problem

You need to store a multi-dimensional associative array of data in a flat file for caching purposes. What will be your solution? Explain.

JSON is simpler and faster than PHP’s serialization format and should be used unless:

  • You’re storing deeply nested arrays: json_decode(): “This function will return false if the JSON encoded data is deeper than 127 elements.”
  • You’re storing objects that need to be unserialized as the correct class. JSON will have no memory of what the object’s original class was (they are always restored as instances of stdClass).
  • You can’t leverage sleep() and wakeup() with JSON
  • You’re interacting with old PHP versions that don’t support json_decode