PHP Passing an array to pack() function

Paolo picture Paolo · Apr 28, 2015 · Viewed 25.9k times · Source

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 ?

Answer

Alex Howansky picture Alex Howansky · Aug 19, 2016

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);