Search code examples
phparrayspack

PHP Passing an array to pack() function


pack() syntax is (from http://php.net/manual/en/function.pack.php)

string pack ( string $format [, mixed $args [, mixed $... ]] )

so assuming I need to pack three bytes

$packed = pack( "c*", 65, 66, 67 );

But what if I have to pack an arbitrary number of bytes?

They could coveniently be stored into an array so I naively tried

$a = array( 65, 66, 67 );
$packed = pack( "c*", $a );

But it doesn't work.

Is there a way to make pack() work with an array ?


Solution

  • At little late to the party, but for future reference, you can use the new ... operator (v5.6+) to explode the array inline:

    $packed = pack("c*", ...$a);