Php Serialize() Function

I did not find any example to meet my needs as khổng lồ what exactly serialize() và unserialize() mean in php? They just give sầu an example - serialize an array and show an output in an unexplained format. It is really hard to lớn understvà the basic concept going through their jargon.

Bạn đang xem: Php serialize() function

EDIT:

"elem 1", "2"=> "elem 2", "3"=>" elem 3");print_r($a);eđến ("");$b=serialize($a);print_r($b);?>output:

Array ( <1> => elem 1 <2> => elem 2 <3> => elem 3 ) a:3:i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";I cannot understand the second output. Besides that, can anyone give an example of a situation that I need khổng lồ serialize a php array before using it?


php
Share
Improve sầu this question
Follow
edited Nov 12 "18 at 12:35
*

Niông chồng
118k20trăng tròn gold badges4444 silver badges7575 bronze badges
asked Dec 27 "11 at 6:42
*

Istiaque AhmedIstiaque Ahmed
5,0471717 gold badges5959 silver badges118118 bronze badges
3
Add a bình luận |

10 Answers 10


Active sầu Oldest Votes
176
A PHPhường array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP. script. If you want lớn persist such a complex data structure beyond a single run of a script, you need to lớn serialize it. That just means lớn put the structure inkhổng lồ a "lower comtháng denominator" that can be handled by things other than PHPhường, like databases, text files, sockets. The standard PHP. function serialize is just a format to lớn express such a thing, it serializes a data structure into a string representation that"s chất lượng to lớn PHP. & can be reversed inlớn a PHP object using unserialize. There are many other formats though, lượt thích JSON or XML.

Xem thêm: phần mềm ios 14.4

Take for example this comtháng problem:

How bởi I pass a PHP array to lớn Javascript?

PHP.. & Javascript can only communicate via strings. You can pass the string "foo" very easily to lớn Javascript. You can pass the number 1 very easily to lớn Javascript. You can pass the boolean values true và false easily khổng lồ Javascript. But how vì chưng you pass this array to Javascript?

Array ( <1> => elem 1 <2> => elem 2 <3> => elem 3 ) The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:

1 : "elem 1", 2 : "elem 2", 3 : "elem 3" Javascript can easily reverse this into lớn an actual Javascript array.

This is just as valid a representation of the same data structure though:

a:3:i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";But pretty much only PHPhường uses it, there"s little support for this format anywhere else.This is very common & well supported as well though:

elem 1 elem 2 elem 3There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to lớn vì chưng this.