How to use chr() Function in a Loop In PHP
The chr() function returns a one-character string containing the character specified by the ASCII value. We can iterate over the byte array and concatenate the characters to form a string.
Example: Below are the approaches to convert byte array to string in PHP:
<?php
$byteArr = [
72, 101, 108, 108, 111, 32,
87, 111, 114, 108, 100
];
$str = '';
foreach ($byteArr as $byte) {
$str .= chr($byte);
}
echo $str;
?>
Output
Hello World
Explanation:
- Initialize an empty string.
- Iterate over the byte array.
- Convert each byte to its corresponding character using chr.
- Concatenate the character to the string.
How to Convert Byte Array to String in PHP?
Given a Byte Array, the task is to convert the byte array to a String in PHP. It is used in various scenarios, such as processing binary data, handling file uploads, or working with data transmission protocols.
Below are the approaches to convert byte array to string in PHP:
Table of Content
- What is a Byte Array?
- Using implode() Function
- Using pack() Function
- Using chr() Function in a Loop
Contact Us