maybe_serialize()
Serializes (turns into a string) the passed data if needed.
This function is commonly used in WordPress when it is not known in advance whether a serialized or simple string is being passed.
The function serializes only arrays, objects, and, for backward compatibility, already serialized strings. Everything else, for example, a simple string, will be returned unchanged.
The serialized string will be serialized again.
$data = 'a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}';
echo maybe_serialize( $data );
// s:50:"a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}";The function can be used early in the WordPress loading process, even before the SHORTINIT constant is defined.
maybe_unserialize() — the reverse function - unserializes the passed value if needed.
Uses: is_serialized()
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.
Returns
Mixed. Serialized data.
Usage
maybe_serialize( $data );
- $data(string/array/object) (required)
- Value to be checked and serialized if necessary.
Examples
#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() maybe serialize code WP 6.9
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;
}