Using WordPress ‘maybe_unserialize()’ PHP function

The maybe_unserialize() WordPress PHP function unserializes data only if it was serialized.

Usage

$result = maybe_unserialize($data);

Input:

$data = 'a:2:{i:0;s:4:"red";i:1;s:5:"green";}';

Output:

Array
(
    [0] => red
    [1] => green
)

Parameters

  • $data (string) – Required. Data that might be unserialized.

More information

See WordPress Developer Resources: maybe_unserialize

Examples

Unserialize an Array

This example shows how to unserialize a serialized array.

$serialized_data = 'a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:5:"grape";}';
$unserialized_data = maybe_unserialize($serialized_data);
print_r($unserialized_data);

Unserialize an Object

This example shows how to unserialize a serialized object.

class Fruit {
    public $name;
    public $color;
}
$fruit = new Fruit();
$fruit->name = 'Apple';
$fruit->color = 'Red';
$serialized_data = serialize($fruit);
$unserialized_data = maybe_unserialize($serialized_data);
print_r($unserialized_data);

Unserialize a String

This example shows how to unserialize a serialized string.

$serialized_data = 's:12:"Hello, World";';
$unserialized_data = maybe_unserialize($serialized_data);
echo $unserialized_data;

Attempt to Unserialize Non-serialized Data

This example shows that the function returns the original data if it was not serialized.

$data = 'Not Serialized Data';
$result = maybe_unserialize($data);
echo $result;

Unserialize a Nested Serialized Data

This example shows how to unserialize a nested serialized data.

$serialized_data = 'a:2:{i:0;s:3:"dog";i:1;s:59:"a:3:{i:0;s:3:"cat";i:1;s:4:"bird";i:2;s:4:"fish";}";}';
$unserialized_data = maybe_unserialize($serialized_data);
$unserialized_data[1] = maybe_unserialize($unserialized_data[1]);
print_r($unserialized_data);