- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
A Preferred method to store PHP arrays (json_encode or serialize)?
This depends on the requirements in hand.
JSON is quicker in comparison to PHP serialization unless the following conditions are met−
- Deeply nested arrays are stored.
- The objects that are stored need to be unserialized to a proper class.
- The interaction is between old PHP versions that don't support json_decode.
The below line of code can be used to store PHP arrays using json_encode−
json_encode($array, JSON_UNESCAPED_UNICODE)
JSON doesn't store the object's original class anywhere, but it can be restored as class instances belonging to stdClass.
Why use json_encode instead of serializing?
- JSON is much more portable in comparison to serialize.
- The features of __sleep() and __wakeup() can't be leveraged using JSON.
- By default, public properties are serialized with JSON. (If PHP version is >=5.4 JsonSerializable can be implemented to change the behavior).
Example
<?php // Array is declared $value = array( "name"=>"name_me", "email"=>"myemail.com" ); // json_encode() function is used $json = json_encode($value); // Displaying output echo($json); ?>
Output
This will produce the following output−
{"name":"name_me","email":"myemail.com"}
Advertisements