maybe_serialize()WP 2.0.5

Serialize data, if needed.

1 time — 0.000003 sec (speed of light) | 50000 times — 0.03 sec (speed of light) | PHP 7.4.25, WP 5.8.2

No Hooks.

Return

Mixed. A scalar data.

Usage

maybe_serialize( $data );
$data(string|array|object) (required)
Data that might be serialized.

Examples

0

#1 An example of what makes a function with different values

// The string will return untouched.
echo maybe_serialize( 'Hello world!' ); // Hello world!

// Numbers (including float), logical true/false/null, will return untouched.
echo maybe_serialize( 55 );    // 55
echo maybe_serialize( 4.560 ); // 4.560

var_dump(  maybe_serialize( true )  ); // true
var_dump(  maybe_serialize( null )  ); // null

// An array or object will return a serialized string.
echo maybe_serialize( [ 1 => 'Hello world!', 'foo' => 'bar' ] );
// a:2:{i:1;s:12: "Hello world!";s:3: "foo";s:3: "bar";}

// The serialized string will be serialized again.
echo maybe_serialize( 'a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}' );
// s:50:"a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}";

Changelog

Since 2.0.5 Introduced.

maybe_serialize() code WP 6.4.3

function maybe_serialize( $data ) {
	if ( is_array( $data ) || is_object( $data ) ) {
		return serialize( $data );
	}

	/*
	 * Double serialization is required for backward compatibility.
	 * See https://core.trac.wordpress.org/ticket/12930
	 * Also the world will end. See WP 3.6.1.
	 */
	if ( is_serialized( $data, false ) ) {
		return serialize( $data );
	}

	return $data;
}