WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/maybe serialize

Contents

Description

Serialize data, if needed.

Usage

<?php maybe_serialize$data ); ?>

Parameters

$data
(mixed) (required) Data that might be serialized.
Default: None

Return Values

(mixed) 
A scalar data

Examples

<?php

// Strings are returned untouched.
$data = 'Hello World!';
echo maybe_serialize( $data );
// Hello World!

// Integers, floats and boolean values are also returned untouched.
$data = 55;
echo maybe_serialize( $data );
// 55

$data = 4.560
echo maybe_serialize( $data );
// 4.560

$data = true;
$data = maybe_serialize( $data );
// $data = true;

$data = null;
$data = maybe_serialize( $data );
// $data = null

// An array or object will be returned as a serialized string.
$data = array( 1 => 'Hello World!', 'foo' => 'bar' );
echo maybe_serialize( $data );
// a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}

// A 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";}";

?>

Notes

  • Data might need to be serialized to allow it to be successfully stored and retrieved from a database in a form that PHP can understand.
  • Confusingly, strings that contain already serialized values are serialized again, resulting in a nested serialization. Other strings are unmodified.

A possible solution to prevent nested serialization is to check if a variable is serialized using <?php if(!is_serialized$data )) { $data maybe_serialize($data); } ?> More info at is_serialized().

Change Log

Since: 2.0.5

Source File

maybe_serialize() is located in wp-includes/functions.php.

Related

See also index of Function Reference and index of Template Tags.