serialize()

serialize() — Generates a storable representation of a value.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

Signature

serialize(mixed $value): string

Parameters

ParameterTypeWhat it takes
$valuemixedThe value to be serialized. serialize() handles all types, except the resource-type and some objects (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.

Return value

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.

Example

A runnable snippet:

// $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. $conn = odbc_connect("webdb", "php", "chicken"); $stmt = odbc_prepare($conn, "UPDATE sessions SET data = ? WHERE id = ?"); $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.. */ } }

See also

unserialize(), var_export(), json_encode()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page serialize() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.