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

Ammending the answer by mario for using pack(): Since PHP 5.5, you can use Argument unpacking via ...

$str = pack('C*', ...$bytes);

The other functions are fine to use, but it is preferred to have readable code.


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


Yet another way:

$str = vsprintf(str_repeat('%c', count($bytes)), $bytes);

Hurray!

Tags:

Php

Ascii