Last Updated: February 25, 2016
· thomaspuppe

json_encode() VS serialize() with PHP Arrays

// UPDATE: The first comment by @michd is the real protip. His hint made this whole thing useless.

json_encode($array) is a fine way to convert a PHP array or object into a string for saving it into a database.

$myArray = array('firstValue', 'secondValue');
$myArrayJsonEncoded = json_encode($myArray);

// results to 

// which can be converted back via 
$myNewArray = json_decode($myArrayJsonEncoded);

But if we want to save assotiative Arrays ...

$myAssotiativeArray = array(
    'firstKey' => 'firstValue',
    'secondKey' => 'secondValue'
$myAssotiativeArrayJsonEncoded = json_encode($myAssotiativeArray);

... this is what happens:

// {"firstKey":"firstValue","secondKey":"secondValue"}


// object(stdClass)[1]
//  public 'firstKey' => string 'firstValue' (length=10)
//  public 'secondKey' => string 'secondValue' (length=11)

Since JavaScript uses Objects for "Assotiative arrays", this makes sense. But if we just want to serialize our PHP Array, we need to use the serialize() function!

$myAssotiativeArraySerialized = serialize($myAssotiativeArray);

// a:2:{s:8:"firstKey";s:10:"firstValue";s:9:"secondKey";s:11:"secondValue";}

Sure, you could always use serialize(). But this results in a less readable and longer string for unassotiative arrays.

Say Thanks

3 Responses
Add your response


If you look at the documentation for json_decode, you'll see that you can pass a second parameter to make it decode these JS objects to associative arrays, so you don't need to use PHP's ugly serialize method.

Storing your data in JSON is also more portable if you ever decide to use in somewhere that's not in PHP, as most popular programming languages have a JSON parsing library somewhere.

over 1 year ago ·

You are totally right. I didn't see that parameter for json_decode. So as long as you know that the JSON Object has been/should be a PHP array (which is the case for my app), this is the better method.

Thank you for the hint.

over 1 year ago ·

@michd That and serialized data using serialize() sometimes doesn't actually unserialize correctly - an issue I've faced in the past several times.

Either way, a properly normalized and planned DB shouldn't technically include serialized data at all...

over 1 year ago ·