Re: [RFC] Add pack()/unpack() support for signed integers with specific endianness

From: Date: Wed, 24 Sep 2025 22:21:44 +0000
Subject: Re: [RFC] Add pack()/unpack() support for signed integers with specific endianness
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-128725@lists.php.net to get a copy of this message
On Sep 24, 2025, at 00:28, Alexandre Daubois <alex.daubois+php@gmail.com> wrote:
> That would be an interesting addition. Given that only those 4 have
> diverged from Perl, that could be great to sync them again. Let's wait
> for other inputs to see if someone agrees with the idea before
> potentially revamping the RFC. I personally like it.

PHP's unpack() is already fundamentally divergent from Perl's in that it returns an
associative array, and requires its format string to be formatted differently from the one used by
pack(). For instance, in Perl, one can write:

    $packed = pack("NNN", 123, 456, 789);
    ($x, $y, $z) = unpack("NNN", $packed);

and have $x = 123, $y = 456, and $z = 789.

In PHP, however, the following code does not work as expected:

    $packed = pack("NNN", 123, 456, 789);
    [$x, $y, $z] = unpack("NNN", $packed);

Instead of returning a list of three integers, it returns an associative array with one key called
"NN"; the other two values aren't unpacked at all. Instead, one must name each of the
fields in the format string and unpack them as an associative array:

    ["x" => $x, "y" => $y, "z" => $z] =
unpack("Nx/Ny/Nz", $packed);

I'd support changes to pack() and/or unpack() to allow them to be used symmetrically, but that
seems like a larger change than what is being proposed here.

-- Andrew F


Thread (33 messages)

« previous php.internals (#128725) next »