A Preferred method to store PHP arrays (json_encode or serialize)?

When storing PHP arrays, choosing between json_encode() and serialize() depends on your specific requirements. Generally, JSON is faster and more portable, but PHP serialization offers better support for complex objects and deeply nested structures.

When to Use json_encode()

JSON is the preferred method for most scenarios because it offers −

  • Better performance for simple arrays
  • Cross-platform compatibility
  • Human-readable format
  • Smaller file size

When to Use serialize()

PHP serialization is better when −

  • Storing deeply nested arrays
  • Objects need to be restored to their original class
  • Using __sleep() and __wakeup() magic methods
  • Working with legacy PHP versions without json_decode()

Example Using json_encode()

Here's how to store a PHP array using json_encode()

<?php
    // Array is declared
    $value = array(
        "name" => "name_me",
        "email" => "myemail@example.com",
        "age" => 25
    );
    
    // json_encode() function is used
    $json = json_encode($value, JSON_UNESCAPED_UNICODE);
    
    // Displaying output
    echo $json;
    echo "<br><br>";
    
    // Decoding back to array
    $decoded = json_decode($json, true);
    print_r($decoded);
?>
{"name":"name_me","email":"myemail@example.com","age":25}

Array
(
    [name] => name_me
    [email] => myemail@example.com
    [age] => 25
)

Example Using serialize()

For comparison, here's the same array using PHP serialization −

<?php
    $value = array(
        "name" => "name_me",
        "email" => "myemail@example.com",
        "age" => 25
    );
    
    // serialize() function is used
    $serialized = serialize($value);
    echo $serialized;
    echo "<br><br>";
    
    // Unserializing back to array
    $unserialized = unserialize($serialized);
    print_r($unserialized);
?>
a:3:{s:4:"name";s:7:"name_me";s:5:"email";s:20:"myemail@example.com";s:3:"age";i:25;}

Array
(
    [name] => name_me
    [email] => myemail@example.com
    [age] => 25
)

Comparison

Feature json_encode() serialize()
Performance Faster Slower
Portability Cross-platform PHP-specific
Object Classes Lost (becomes stdClass) Preserved
File Size Smaller Larger

Conclusion

Use json_encode() for most array storage needs due to its speed and portability. Choose serialize() only when you need to preserve object classes or handle complex nested structures with specific PHP features.

Updated on: 2026-03-15T08:26:21+05:30

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements