Why unpack() function in PHP returns an array of binary data starting with the array index 1.
$str = "PHP";
$binary_data = unpack("C*",$str);
print_r($binary_data);
The above PHP scripts prints as below:
Array ( [1] => 80 [2] => 72 [3] => 80 )
By default in PHP the array key starts from 0.
The unpack() function unpacks data from a binary string.
PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.
Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.
The array is an associative array with named keys, not a regular array with numeric keys. The idea is that you will name each format code and the result array will use those names as the array keys.
For example:
<?php
$str = "PHP";
$binary_data = unpack("C*letter",$str);
print_r($binary_data);
Result:
Array
(
[letter1] => 80
[letter2] => 72
[letter3] => 80
)
From the PHP manual:
The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash
/
. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.Example #1 unpack() example
<?php $binarydata = "\x04\x00\xa0\x00"; $array = unpack("cchars/nint", $binarydata); ?>
The resulting array will contain the entries "chars" with value 4 and "int" with 160.
Example #2 unpack() example with a repeater
<?php $binarydata = "\x04\x00\xa0\x00"; $array = unpack("c2chars/nint", $binarydata); ?>
The resulting array will contain the entries "chars1", "chars2" and "int".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With