How can I convert array of bytes to a string in PHP?
You have an array of integers representing byte values, and you need to transform them into a readable string. In PHP, this is a common task when dealing with network packets, serialized data, or binary file streams. The most direct approach depends entirely on the character encoding of your data. If those bytes represent standard ASCII text, chr() provides a quick solution. However, modern applications almost exclusively use UTF-8, making chr() insufficient for anything beyond single-byte characters.
The core mechanic here is that an array like [65, 66, 67] represents the decimal values of characters 'A', 'B', and 'C'. To convert this to a string, you must iterate through the array and construct the result. The simplest way to handle ASCII-only data is using chr() combined with implode(). This function converts each integer in the array to its corresponding character and joins them together.
$bytes = [65, 66, 67]; // Represents "ABC"
$string = implode('', array_map('chr', $bytes));
// Result: "ABC"
While this works for simple cases, relying on chr() is risky for real-world scenarios. It assumes every byte maps to a valid single-byte character in the ASCII range (0-127). If your data contains extended characters or multi-byte sequences, this method will truncate data or produce mojibake. For instance, if you have UTF-8 encoded bytes representing an emoji or a special symbol, chr() will not reconstruct the string correctly because it treats each byte as an independent character.
When dealing with UTF-8 or other multi-byte encodings, you need a different strategy. The standard library function pack() is designed specifically for this conversion. You can pack an array of bytes into a string by specifying the format string 'H*' if your input is hexadecimal, or simply iterating if you have raw integer values. However, the most robust method provided by PHP's core is the pack() function with the appropriate format specifier when working directly from binary data, but for converting a decimal array to a UTF-8 string, we often need to ensure the resulting bytes are interpreted correctly by the output context.
If your source material guarantees that the byte array is valid UTF-8, you can use pack() with a specific format, but a cleaner approach for raw integer arrays in modern PHP versions involves ensuring the output stream or variable respects the encoding. A more explicit way to handle this without assuming ASCII is to verify the encoding first. If you know the data is Latin-1 (ISO-8859-1), chr() works up to byte 255. For UTF-8, you must ensure the resulting string is treated as UTF-8.
$bytes = [0xE2, 0x9C, 0x93]; // Represents "â¥" (heart) in UTF-8
$string = implode('', array_map('chr', $bytes));
// If echo'ed without proper encoding headers, this might render as �
echo mb_convert_encoding($string, 'UTF-8', 'ISO-8859-1') ?? $string;
In practice, the mb_convert_encoding function is your safety net. It attempts to map the constructed string from a single-byte interpretation back to UTF-8 if necessary, though this requires careful handling of the intermediate encoding assumption. A safer pattern for strictly binary data that you know is valid UTF-8 is to use pack() with a format string that accepts a list of bytes, but PHP's pack expects hex strings or specific binary structures by default for complex cases.
The most reliable method for converting an array of decimal integers to a UTF-8 string without intermediate encoding assumptions is often handled by third-party libraries or by ensuring the environment is strictly configured. If you are using Laravel, you can leverage the str() helper functions which respect the global encoding settings, but the underlying logic remains: if the bytes are multi-byte, chr() fails to reconstruct them because it lacks context about byte order and continuation bits.
If your application frequently processes binary data, consider using a dedicated package like guzzlehttp/psr7 or similar stream helpers that handle buffer reading and encoding explicitly. Always validate that your input array contains only valid byte values (0â255) before attempting conversion, as passing invalid integers will result in warnings or unexpected characters. Remember that the choice between chr() and more complex packing methods hinges on whether your data is truly single-byte ASCII or a multi-byte encoding like UTF-8.