Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
pack() function in PHP
The pack() function in PHP converts data into a binary string according to a specified format. This function is useful for creating binary data structures, network protocols, or file formats that require specific byte arrangements.
Syntax
pack(format, args)
Parameters
-
format − The format string specifying how to pack the data. Common format codes include:
a − NUL-padded string
A − SPACE-padded string
c − signed char (8-bit)
C − unsigned char (8-bit)
s − signed short (16-bit, machine byte order)
S − unsigned short (16-bit, machine byte order)
i − signed integer (machine dependent)
I − unsigned integer (machine dependent)
l − signed long (32-bit, machine byte order)
L − unsigned long (32-bit, machine byte order)
f − float (machine dependent)
d − double (machine dependent)
args − One or more values to be packed according to the format
Return Value
Returns a binary string containing the packed data.
Basic Example
Here's how to pack three unsigned characters into a binary string −
<?php
$binary = pack("C3", 80, 72, 80);
echo $binary;
?>
PHP
String Packing Example
Packing strings with different padding methods −
<?php
// NUL-padded string
$packed1 = pack("a10", "Hello");
echo "NUL-padded: " . bin2hex($packed1) . "<br>";
// SPACE-padded string
$packed2 = pack("A10", "Hello");
echo "SPACE-padded: " . bin2hex($packed2) . "<br>";
?>
NUL-padded: 48656c6c6f0000000000 SPACE-padded: 48656c6c6f2020202020
Integer Packing Example
Packing different integer types −
<?php
// Pack as unsigned short (16-bit)
$short = pack("S", 1234);
echo "Short (16-bit): " . bin2hex($short) . "<br>";
// Pack as unsigned long (32-bit)
$long = pack("L", 123456);
echo "Long (32-bit): " . bin2hex($long) . "<br>";
?>
Short (16-bit): d204 Long (32-bit): 40e20100
Conclusion
The pack() function is essential for binary data manipulation in PHP. Use format codes like "C" for unsigned chars, "S" for shorts, and "L" for longs to create structured binary data for protocols or file formats.
