Here is one more quick article about to store binary data in strings with the use of two core functions in PHP.
Like, You want to parse a string that have values encoded as a binary structure or want to encode values into a string.Let’s see an example that you want to store numbers in the binary representation instead of sequences of ASCII characters.so you need to use the pack() function to store binary data in a string.
What is pack() method?
pack() method is mainly used to store the data in binary form in PHP
$pack_data = pack('S3',1994,54,225);
The first argument into a pack() function is the format as a string which shows how to encode the data and other passed arguments are the data we want to pack as the binary string. The s3 format produces the three unsigned short 16-bit numbers in the byte as the order from its input data.Given input 1994,54,225 returns eight bytes
What is unpack() function?
unpack() transforms binary data into an associative array based on the format.
array unpack(string format, string binary_string)
Here, Format parameter is used when unpacking and binary_string is used to unpack Binary string.This function parses a binary string according to a user-defined format.
It returns an associative array and FALSE on error.
Now, Let’s see unpack() function
unpack() function SYNTAX
$return = unpack('S3',$pack_data); print_r($return);
The first argument into an unpack() function is also a format as a string and second argument is encoded data that you want to decode.and the output of the unpack() function will be a decoded data as associative array.
Array (  => 1994  => 54  => 225 )
You can use different format characters and their count can be followed by an array key in unpack() function.
$return = unpack('S3no',$pack_data); print_r($return);
Array ( [no1] => 1994 [no2] => 54 [no3] => 225 )
Even you can use multiple formats and can separate them by a slash / with unpack() function.You can also use unpack( ) as a substitute for substr( ) method to extract fields.Both substr( ) and unpack( ) function have equivalent capabilities when the fixed-width fields but unpack( ) is the better solution when the elements of the fields aren’t just strings.
$return = unpack('S1a/S1b/S1c',$pack_data); print_r($return);
Array ( [a] => 1994 [b] => 54 [c] => 225 )
There are many format characters that can be used with the pack( ) and unpack( ) function. you can see format character in PHP Manual. Do you have any question about pack() and unpack() function? Let me know in comment section.