Last Updated: October 11, 2021
·
65.82K
· 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 
["firstValue","secondValue"]

// 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"}

json_decode($myAssotiativeArrayJsonEncoded)

// 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.

1 Response
Add your response

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 ·