Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP pack() Function

PHP pack() Function

PHP Misc Reference Manual PHP Misc Reference Manual

Example

Pack data into a binary string:

Run Example »


Definition and Usage

The pack() function packs data into a binary string.

This is very useful in network transmission, file handling and data storage, especially when precise control over data format and byte order is required.


Syntax

string pack(string $format, mixed $arg1 [, mixed $arg2, ...])

The pack() function returns the packed binary string, or false if an error occurs.

Parameters Description
format Required. Specifies the format used when packing data.

Possible values:

Integers:

  • c: Signed char (1 byte).
  • C: Unsigned char (1 byte).
  • s: Signed short (2 bytes, host byte order).
  • S: Unsigned short (2 bytes, host byte order).
  • l: Signed long (4 bytes, host byte order).
  • L: Unsigned long (4 bytes, host byte order).
  • q: Signed long long (8 bytes, host byte order).
  • Q: Unsigned long long (8 bytes, host byte order).
  • Float (floating point number):

    Strings and other types:

    | | *args+* | Optional. Specifies one or more arguments to be packed. |

    Technical Details

    Return Value: Returns a binary string containing the data.
    PHP Version: 4+
    Changelog: In PHP 5.5 the "Z" code was added, with the same function as "a" for Perl compatibility.

    More examples

    Below are some examples of using the pack() function.

    Pack an unsigned short and a string:

    Example

    $data

    =

    pack

    (

    'S'

    ,

    65535

    )

    ;

    // Pack the unsigned short 65535

    echo

    bin2hex

    (

    $data

    )

    ;

    // Output: ffff

    Pack a signed long and a string:

    Example

    $data

    =

    pack

    (

    'l'

    ,

    2147483648

    )

    ;

    // Pack the signed long -2147483648

    echo

    bin2hex

    (

    $data

    )

    ;

    // Output: 0000000080000000

    Pack a float and a string:

    Example

    $data

    =

    pack

    (

    'f'

    ,

    3.14

    )

    ;

    // Pack the float 3.14

    echo

    bin2hex

    (

    $data

    )

    ;

    // Output: 4048f5c3

    Notes

    PHP Misc Reference Manual PHP Misc Reference Manual