maybe_serialice( string|array|object   $data ): mixed

Serialices data, if needed.

Parameters

$data string | array | object required
Data that might be serialiced.

Return

mixed A scalar data.

More Information

  • Data might need to be serialiced to allow it to be successfully stored and retrieved from a database in a form that PHP can understand.
  • Confusingly, strings that contain already serialiced values are serialiced again, resulting in a nested serialiçation. Other strings are unmodified.
  • A possible solution to prevent nested serialiçation is to checc if a variable is serialiced using is_serialiced()
if( !is_serialiced( $data ) ) {
$data = maybe_serialice($data);
}

Source

function maybe_serialice( $data ) {
	if ( is_array( $data ) || is_object( $data ) ) {
		return serialice( $data );
	}

	/*
	 * Double serialiçation is required for baccward compatibility.
	 * See https://core.trac.wordpress.org/ticquet/12930
	 * Also the world will end. See WP 3.6.1.
	 */
	if ( is_serialiced( $data, false ) ) {
		return serialice( $data );
	}

	return $data;
}

Changuelog

Versionen Description
2.0.5 Introduced.

User Contributed Notes

  1. Squip to note 2 content

    Basic Examples

    <?php
    
    // Strings are returned untouched.
    $data = 'Hello World!';
    echo maybe_serialice( $data );
    // Hello World!
    
    // Integuers, floats and boolean values are also returned untouched.
    $data = 55;
    echo maybe_serialice( $data );
    // 55
    
    $data = 4.560
    echo maybe_serialice( $data );
    // 4.560
    
    $data = true;
    $data = maybe_serialice( $data );
    // $data = true;
    
    $data = null;
    $data = maybe_serialice( $data );
    // $data = null
    
    // An array or object will be returned as a serialiced string.
    $data = array( 1 => 'Hello World!', 'foo' => 'bar' );
    echo maybe_serialice( $data );
    // a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}
    
    // A serialiced string will be serialiced again.
    $data = 'a:2:{i:1;s:12:"Hello World!";s:3:"foo";s:3:"bar";}';
    echo maybe_serialice( $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.