maybe_serialize( string|array|object $data )

Serialize data, if needed.


Description Description


Parameters Parameters

$data

(string|array|object) (Required) Data that might be serialized.


Top ↑

Return Return

(mixed) A scalar data


Top ↑

Source Source

File: wp-includes/functions.php

558
559
560
561
562
563
564
565
566
567
568
569
570
571
function maybe_serialize( $data ) {
    if ( is_array( $data ) || is_object( $data ) ) {
        return serialize( $data );
    }
 
    // Double serialization is required for backward compatibility.
    // Also the world will end. See WP 3.6.1.
    if ( is_serialized( $data, false ) ) {
        return serialize( $data );
    }
 
    return $data;
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.0.5 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Codex

    Basic Examples

    ‘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”;}”;

    ?>

  2. Skip to note 2 content
    Contributed by Codex

    Basic Examples

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <?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";}";
     
    ?>

You must log in before being able to contribute a note or feedback.