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
<?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

Similar Reads

What is a Byte Array?

A byte array is a sequence of bytes, where each byte is an 8-bit unsigned integer. In PHP, byte arrays are typically represented using strings since PHP strings are essentially sequences of bytes....

Using implode() Function

The implode() function is used to join array elements with a string. By using an empty string as the separator, we can join the elements of a byte array into a single string....

Using pack() Function

The pack() function is used to pack data into a binary string. Using the format character C*, we can convert an array of bytes into a string....

Using chr() Function in a Loop

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

Contact Us