PHP inconsistency with unpack

I’m normally a big fan of PHP for a number of reasons, so today is a sad day to me as I am making my first contribution to LOLPHP.

For the last few days I have been working on a lot of socket-related tasks and had to make use of the pack() and unpack() functions.

For those of you, who have never used these functions: the pack function packs a number of variables into a binary string. For example you could store 8 boolean variables on just one byte this way.

Now, while unpacking my data I noticed a rather peculiar behavior. Let’s see:

php > var_dump(unpack('n2', pack('n2', 1234, 1234)));
array(2) {

As you can see, the result array of unpack is indexed from 1 instead of the usual 0. (Most PHP functions return arrays indexed from 0.) In other words if you want to use the result in distinct variables, you would have to write the following:

list(,$var1, $var2) = unpack('n2', $packedData);

See the comma in front of $var1? That’s a rather error-prone thing to do, so I recommend naming your indexes if practical.

O yeah, there is a bug for it.

2 thoughts on “PHP inconsistency with unpack

  1. Graaf Dyper

    Just array_values(unpack('n2', $packedData)), or

    function funpack() {
        return array_values(call_user_func_array('unpack', func_get_args()));

    Still sad, though.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>