How can pack() and unpack() functions be used to handle binary data in PHP?

Pack() and unpack() functions in PHP can be used to handle binary data by converting data between binary strings and PHP variables. Pack() function takes PHP variables and packs them into a binary string, while unpack() function takes a binary string and unpacks it into PHP variables. This can be useful when working with binary data such as network protocols or file formats.

// Using pack() to convert PHP variables to binary data
$int = 10;
$float = 3.14;
$string = "hello";
$binaryData = pack("lfs", $int, $float, $string);

// Using unpack() to convert binary data to PHP variables
$data = unpack("linteger/ffloat/sstring", $binaryData);
echo $data['integer']; // Output: 10
echo $data['float']; // Output: 3.14
echo $data['string']; // Output: hello