PHP serialize() Function

Quick summary: The PHP serialize() function generates a storable representation of a value.

PHP serialize() Syntax

serialize(mixed $value): string
PHP

PHP serialize() Basic examples

$data = ['a'=>1];
var_dump(serialize($data));
PHP
Output:
string(18) "a:1:{s:1:"a";i:1;}"

Serializes arrays into strings.

PHP serialize() Real-world usage

$session = ['user'=>'admin'];
$stored = serialize($session);
var_dump($stored);
PHP
Output:
string(29) "a:1:{s:4:"user";s:5:"admin";}"

Stores structured data in sessions or cache.

PHP serialize() Edge cases

var_dump(serialize(function(){}));
PHP
Output:
Fatal error: Serialization of 'Closure' is not allowed

Closures cannot be serialized.

PHP serialize() Common mistakes

Serializing untrusted data

Serialized data can be unsafe.

Incorrect
unserialize($_GET['data']);
Correct
json_decode($_GET['data'], true);

Avoid unserializing untrusted input.

PHP serialize() Frequently Asked Questions

What does serialize() do in PHP?

serialize() converts a PHP value into a storable string.

What types can be serialized?

Arrays, objects, strings, numbers, and more.

Use case of serialize()?

Storing complex data structures.

Does serialize() preserve types?

Yes, type information is stored.

Is serialize() safe?

Safe for storage, but unserialize() can be risky.

Difference from json_encode()?

serialize() preserves PHP-specific types.

Can objects be serialized?

Yes.

Performance of serialize()?

Moderate, slower than JSON.

Can resources be serialized?

No.

Common mistake?

Using serialize for interoperability.

Can serialize() fail?

Yes for unsupported types.

Best alternative?

json_encode for cross-language use.

PHP serialize() Related PHP Functions