maybe_unserialize()WP 2.0.0

Unserialize data only if it was serialized or returns the original value.

This function checks if the passed value is serialized ( php function serialize() ):

  • if it is, then unserialize() will be applied to it.
  • if not, the function will simply return the initial value.

The opposite counterpart to this function is maybe_serialize() - it serializes data and returns it if an array/object is passed.

Works early in the WordPress boot phase, even before the SHORTINIT constant.

See also the custom function maybe_json_decode().

1 time — 0.000047 sec (very fast) | 50000 times — 1.21 sec (fast) | PHP 7.1.2, WP 4.7.4

No Hooks.

Return

Mixed. Unserialized data can be any type.

Usage

maybe_unserialize( $data );
$data(string) (required)
Initial data to check and unserialize, if necessary.

Examples

0

#1 Demo

$res = maybe_unserialize( 'a:1:{s:3:"foo";i:15;}' );

/*
Array (
	[foo] => 15
)
*/

$res = maybe_unserialize( 'simple string' ); //> simple string

$res = maybe_unserialize( 123 ); //> 123
0

#2 Usage maybe_unserialize() in WP

In WordPress, this function is used in many places and more often than not there is no need to care about what data we place or get from the database. Let's say when you save an array to a post custom field with update_post_meta(), the data is automatically serialized when you save it and deserialized when you get it using get_post_meta(). The same happens when saving and retrieving options: see add_option(), get_option().

However, in some cases, the development of plugins or themes, you need to do this check manually, and here you can use this function and its analog [maybe_serialize()] (/function/maybe_serialize).

Suppose we saved data to the database, which is structured data: an array/object. When we retrieve this data, we need it in a structured form. To do this, we get the data and pass it through the maybe_unserialize() function:

// $value - is string as serialized object

$value = maybe_unserialize( $value );

// $value now become a real object

// now we can use it: $value->some_prop

Changelog

Since 2.0.0 Introduced.

maybe_unserialize() code WP 6.7.1

function maybe_unserialize( $data ) {
	if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
		return @unserialize( trim( $data ) );
	}

	return $data;
}