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 )
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".
chars1 instead of chars0 etc in the provided example). Also all arrays in php are technically associative.
pack, notunpack"PHP"is a legitimate test ofunpack(). There's no reason to believe the OP meant to pack rather than unpack.