Change language

How to use php serialize () and unserialize () function

More often than not, we need to store a complex array in a database or in a file from PHP. Some of us were probably looking for some kind of built-in function to accomplish this task. Complex arrays - they are arrays with elements of more than one data type or array. But we already have a convenient solution to deal with this situation.Serialize() function:serialize() - it is a built-in PHP function that is used to serialize a given array. The serialize() function takes one parameter, which is the data we want to serialize, and returns a serialized string.
  • Syntax:
    serialize ($values_in_form_of_array) 
  • The program below illustrates the Serialize() function. 
    Program :  
    // Complex array $myvar = array ( ’hello’ , 42, array (1, ’two’ ), ’apple’);  
    // Convert to string $string = serialize ( $myvar );  
    // Print serialized data echo $string ;  
    ?>
  • Exit:
    a: 4: {i: 0; s: 5: "hello"; i: 1; i: 42; i: 2; a: 2: {i: 0; i: 1; i: 1; s: 3: "two";} i: 3; s: 5: "apple";} 
Unserialize() function:unserialize() - this is a built-in php function that is used to deserialize a given serialized array to revert to the original complex array value, $myvar.
  • Syntax:
    unserialize ($serialized_array ) 
  • The program below illustrates the serialize() and unserialize() functions:
    Program :  
    // Complex array $myvar = array ( ’hello’ , 42, arra y (1, ’two’ ), ’apple’) ;  
    // Serialize the above data $string = serialize ( $myvar );  
    // deserialize data into $string $newvar = unserialize ( $string );  
    // Print unserialized data print_r ( $newvar );  
    ?>
  • Exit:
    Array ([0] = > hello [1] = > 42 [2] = > Array ([0] = > 1 [1] = > two) [3] = > apple) 
Note:for more in-depth knowledge, you can check out PHP | Serializing data articles.

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method