Storing an array in MySQL from PHP

There has been a number of times I wanted to store an array in a database. There was no need to split the data up and save it into individual cell. Maybe it was just debugging data or I wanted to store all the extra stuff a payment processor returns. There are really two ways to do this.

Encode it as JSON, which is generally my preference these days, most because it makes it easy to do anything I want with it later in php or if past to javascript, etc.

json_encode($array);

 

Or you can serialize it

serialize($array)

Here are a few reasons why

Pro JSON:

  • The JSON data can be used by many different languages, not just PHP
  • JSON data is human readable and writable.
  • It takes up less space
  • It is faster to encode JSON than to serialize

Pro Serialized Array:

  • It is faster do unserialize than to JSON decode

Tags: MySQL, PHP