- serialize
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 33 notes
- 5 Ways To Convert Array To String In PHP
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- ARRAY TO STRING
- 1) IMPLODE FUNCTION
- 2) ARRAY REDUCE
- 3) MANUAL LOOP
- 4) JSON ENCODE
- 5) SERIALIZE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- SUMMARY
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
serialize
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize() .
Parameters
The value to be serialized. serialize() handles all types, except the resource -type and some object s (see note below). You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serializing will also be stored. Any other reference will be lost.
When serializing objects, PHP will attempt to call the member functions __serialize() or __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __unserialize() or __wakeup() member function is called.
Note:
Object’s private members have the class name prepended to the member name; protected members have a ‘*’ prepended to the member name. These prepended values have null bytes on either side.
Return Values
Returns a string containing a byte-stream representation of value that can be stored anywhere.
Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.
Examples
Example #1 serialize() example
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialize() to store
// it in a database at the end of the request.
?php
$conn = odbc_connect ( «webdb» , «php» , «chicken» );
$stmt = odbc_prepare ( $conn ,
«UPDATE sessions SET data = ? WHERE > );
$sqldata = array ( serialize ( $session_data ), $_SERVER [ ‘PHP_AUTH_USER’ ]);
if (! odbc_execute ( $stmt , $sqldata )) $stmt = odbc_prepare ( $conn ,
«INSERT INTO sessions (id, data) VALUES(?, ?)» );
if (! odbc_execute ( $stmt , array_reverse ( $sqldata ))) /* Something went wrong.. */
>
>
?>
Notes
Note:
Note that many built-in PHP objects cannot be serialized. However, those with this ability either implement the Serializable interface or the magic __serialize()/__unserialize() or __sleep()/__wakeup() methods. If an internal class does not fulfill any of those requirements, it cannot reliably be serialized.
There are some historical exceptions to the above rule, where some internal objects could be serialized without implementing the interface or exposing the methods.
When serialize() serializes objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.
See Also
- unserialize() — Creates a PHP value from a stored representation
- var_export() — Outputs or returns a parsable string representation of a variable
- json_encode() — Returns the JSON representation of a value
- Serializing Objects
- __sleep()
- __wakeup()
- __serialize()
- __unserialize()
User Contributed Notes 33 notes
/*
Anatomy of a serialize()’ed value:
?
Boolean
b:value; (does not store «true» or «false», does store ‘1’ or ‘0’)
Object
O:strlen(object name):object name:object size:
String values are always in double quotes
Array keys are always integers or strings
«null => ‘value'» equates to ‘s:0:»»;s:5:»value»;’,
«true => ‘value'» equates to ‘i:1;s:5:»value»;’,
«false => ‘value'» equates to ‘i:0;s:5:»value»;’,
«array(whatever the contents) => ‘value'» equates to an «illegal offset type» warning because you can’t use an
array as a key; however, if you use a variable containing an array as a key, it will equate to ‘s:5:»Array»;s:5:»value»;’,
and
attempting to use an object as a key will result in the same behavior as using an array will.
*/
?>
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that’s missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let’s say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
I’ve encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you’ve serialized.
That’s not to say serialize() is useless. It’s not. A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others. Just don’t abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
I did some testing to see the speed differences between serialize and json_encode, and my results with 250 iterations are:
PHP serialized in 0.0651714730263 seconds average
JSON encoded in 0.0254955434799 seconds average
json_encode() was roughly 155.62% faster than serialize()
Test took 27.2039430141 seconds with 300 iretations.
PHP serialized in 0.0564563179016 seconds average
JSON encoded in 0.0249140485128 seconds average
json_encode() was roughly 126.60% faster than serialize()
Test took 24.4148340225 seconds with 300 iretations.
From all my tests it looks like json_encode is on average about 120% faster (sometimes it gets to about 85% and sometimes to 150%).
Here is the PHP code you can run on your server to try it out:
// fillArray function myde by Peter Bailey
function fillArray ( $depth , $max ) static $seed ;
if ( is_null ( $seed )) $seed = array( ‘a’ , 2 , ‘c’ , 4 , ‘e’ , 6 , ‘g’ , 8 , ‘i’ , 10 );
>
if ( $depth < $max )$node = array();
foreach ( $seed as $key ) $node [ $key ] = fillArray ( $depth + 1 , $max );
>
return $node ;
>
return ’empty’ ;
>
function testSpeed ( $testArray , $iterations = 100 )
$json_time = array();
$serialize_time = array();
$test_start = microtime ( true );
for ( $x = 1 ; $x $start = microtime ( true );
json_encode ( $testArray );
$json_time [] = microtime ( true ) — $start ;
$start = microtime ( true );
serialize ( $testArray );
$serialize_time [] = microtime ( true ) — $start ;
>
$test_lenght = microtime ( true ) — $test_start ;
$json_average = array_sum ( $json_time ) / count ( $json_time );
$serialize_average = array_sum ( $serialize_time ) / count ( $serialize_time );
$result = «PHP serialized in » . $serialize_average . » seconds average
» ;
$result .= «JSON encoded in » . $json_average . » seconds average
» ;
if ( $json_average < $serialize_average )$result .= "json_encode() was roughly " . number_format ( ( $serialize_average / $json_average - 1 ) * 100 , 2 ). "% faster than serialize()
» ;
> else if ( $serializeTime < $jsonTime )$result .= "serialize() was roughly " . number_format ( ( $json_average / $serialize_average - 1 ) * 100 , 2 ). "% faster than json_encode()
» ;
> else $result .= «No way!
» ;
>
$result .= «Test took » . $test_lenght . » seconds with » . $iterations . » iterations.» ;
// Change the number of iterations (250) to lower if you exceed your maximum execution time
echo testSpeed ( fillArray ( 0 , 5 ), 250 );
5 Ways To Convert Array To String In PHP
Welcome to a beginner’s tutorial on how to convert an array to a string in PHP. So you need to quickly create a string from data in an array?
- $STR = implode(«SEPARATOR», $ARR);
- $STR = array_reduce($ARR, «FUNCTION»);
- Manually loop and create a string.
- $STR = «»;
- foreach ($ARR as $i)
- $STR = json_encode($ARR);
- $STR = serialize($ARR);
That covers the basics, but just how does each one of them work? Need more actual examples? Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
ARRAY TO STRING
All right, let us now get started with the various ways to convert a string to an array in PHP.
1) IMPLODE FUNCTION
// (A) THE ARRAY $arr = ["Red", "Green", "Blue"]; // (B) NO SEPARATOR - SIMPLY JOIN ALL ELEMENTS $str = implode($arr); echo $str; // RedGreenBlue // (C) SEPARATOR SPECIFIED $str = implode(", ", $arr); echo $str; // Red, Green, Blue
This should be pretty easy to understand. The implode() function simply takes an array and combines all the elements into a flat string. Just remember to specify a SEPARATOR , or all the elements will be smushed into a string without any spaces.
2) ARRAY REDUCE
// (A) REDUCTION FUNCTION function reduction ($carry, $item) < if ($item !="Green") < $carry .= "$item, "; >return $carry; > // (B) THE ARRAY $arr = ["Red", "Green", "Blue"]; // (C) REDUCE ARRAY $str = array_reduce($arr, "reduction"); $str = substr($str, 0, -2); echo $str; // Red, Blue
The usage of the array_reduce() function may not obvious at the first glance, but the general idea is to reduce an array down to a single string – By using a given custom REDUCTION function – In this one, we can pretty much set any rules, do any “special processing”.
3) MANUAL LOOP
// (A) THE ARRAY $arr = ["Red", "Green", "Blue"]; // (B) MANUAL LOOP & BUILD STRING $str = ""; foreach ($arr as $item) < $str .= "$item, "; >$str = substr($str, 0, -2); echo $str; // Red, Green, Blue
Well, this should be pretty self-explanatory. Just loop through an array, and create a string manually.
4) JSON ENCODE
// (A) THE ARRAY $arr = ["Red", "Green", "Blue"]; // (B) JSON ENCODE ARRAY $str = json_encode($arr); echo $str; // ["Red","Green","Blue"]
For the beginners, JSON (Javascript Object Notation) in simple terms, is to convert an array into an equivalent data string – Very handy if you want to pass an array from Javascript to PHP (or vice-versa). In PHP, we use json_encode() to turn an array into a string, and json_decode() to turn the string back to an array.
5) SERIALIZE
// (A) THE ARRAY $arr = ["Red", "Green", "Blue"]; // (B) PHP SERIALIZED ARRAY $str = serialize($arr); echo $str; // a:3:
Finally, this is PHP’s “version of JSON encode”. Yep, the serialize() function can pretty much turn any array, object, function, and whatever into a string. Very convenient if you want to store something in the database, and retrieve it for later use.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
SUMMARY
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.