7

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 )

4
  • 1
    not sure why, but you could run array_values to re-index the keys if it is really a problem Commented Dec 23, 2013 at 15:41
  • 1
    Your code is trying to convert a string to binary data, hence you have to use pack, not unpack Commented Dec 23, 2013 at 15:44
  • I tried with this($str = "0x123";) binary data, this also returns with array index 1. Commented Dec 23, 2013 at 15:45
  • 3
    @Hanky웃Panky Unpacking the string "PHP" is a legitimate test of unpack(). There's no reason to believe the OP meant to pack rather than unpack. Commented Dec 23, 2013 at 15:53

1 Answer 1

5

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".

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't really answer why it starts from 1 instead of 0 (chars1 instead of chars0 etc in the provided example). Also all arrays in php are technically associative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.