Using WordPress ‘maybe_serialize()’ PHP function

The maybe_serialize() WordPress PHP function checks if data needs to be serialized and serializes it if necessary.



Custom Example

Input: $data = array("a" => 1, "b" => 2);

Output: 'a:2:{s:1:"a";i:1;s:1:"b";i:2;}'


  • $data (string|array|object) – The data that might need to be serialized.

More information

See WordPress Developer Resources: maybe_serialize


Serialize a string

Serializing a string returns the original string.

$data = 'Hello World!';
$result = maybe_serialize($data);
echo $result; // Hello World!

Serialize a number

Serializing a number returns the original number.

$data = 42;
$result = maybe_serialize($data);
echo $result; // 42

Serialize a boolean value

Serializing a boolean value returns the original boolean value.

$data = true;
$result = maybe_serialize($data);
echo $result ? 'true' : 'false'; // true

Serialize an array

Serializing an array returns a serialized string.

$data = array('key' => 'value', 'number' => 123);
$result = maybe_serialize($data);
echo $result; // a:2:{s:3:"key";s:5:"value";s:6:"number";i:123;}

Serialize a serialized string

Serializing an already serialized string returns a serialized version of the original serialized string.

$data = 'a:2:{s:3:"key";s:5:"value";s:6:"number";i:123;}';
$result = maybe_serialize($data);
echo $result; // s:44:"a:2:{s:3:"key";s:5:"value";s:6:"number";i:123;}";