How can I convert array of bytes to a string in PHP?

If by array of bytes you mean:

$bytes = array(255, 0, 55, 42, 17,    );

array_map()

Then it’s as simple as:

$string = implode(array_map("chr", $bytes));

foreach()

Which is the compact version of:

$string = "";
foreach ($bytes as $chr) {
    $string .= chr($chr);
}
// Might be a bit speedier due to not constructing a temporary array.

pack()

But the most advisable alternative could be to use pack("C*", [$array...]), even though it requires a funky array workaround in PHP to pass the integer list:

$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));

That construct is also more useful if you might need to switch from bytes C* (for ASCII strings) to words S* (for UCS2) or even have a list of 32bit integers L* (e.g. a UCS4 Unicode string).

Leave a Comment