Convert ASCII Codes to String using PHP

This article will provide an explanation for how to convert ASCII Codes to String using PHP.

Previously, we have explained how to convert String to ASCII Code using PHP function named ord().

In this article, we are going to use a PHP function called chr() to convert ASCII Codes to String.

The chr() PHP function takes an ASCII code as its argument and returns one character string.

The argument can be ASCII value in decimal, hex, and octal.

Syntax: chr(ASCII value)

The following code is an example of how to use chr() PHP function:

<?php
   echo chr(44);       // ASCII value in decimal
   echo chr(044);     // ASCII value in octal
   echo chr(0x44);   // ASCII value in hex
?>

Output:
,
$
D

Supposed we have a sequence of ASCII codes separated by space. To convert it to String, we need to split that ASCII code; by using a loop and explode() PHP function, we can convert every ASCII code to String.

The following code is the example of how to convert more than just one ASCII Code to String:

<?php
    $ascii_codes = "84 114 121 105 110 103 32 84 104 101 32 65 83 67 73 73 32 67 111 100 101 32 116 111 32 83 116 114 105 110 103 32 67 111 110 118 101 114 116 101 114 ";
    
    $array_ascii = explode(" ", $ascii_codes);
    $array_len = count($array_ascii);
    
    for($i = 0; $i < $array_len; $i++){
           echo chr($array_ascii[$i]);
    }
?>

Output:
Trying The ASCII Code to String Converter

As seen in the code example above, the variable $ascii_codes store ASCII Code which is “84 114 121 105 110 103 32 84 104 101 32 65 83 67 73 73 32 67 111 100 101 32 116 111 32 83 116 114 105 110 103 32 67 111 110 118 101 114 116 101 114 “.

At line 4, we use the explode() PHP function to split the ASCII Codes store in the variable $ascii_codes and store it in the $array_ascii variable as an array.

At line 5, the count() PHP function counts all elements in an array.

At line 8, convert each ASCII code that stores in the $array_ascii variable to String using chr() PHP function.

The PHP code above will produce String output: “Trying The ASCII Code to String Converter”

Conclusion

The chr() PHP function is used to convert a single ASCII Code to a specific character. The function can accept a single ASCII Code in three different types, binary, hex, and octal.

Try our free online ASCII converter tools:

  1. String to ASCII Code Converter (in decimal)
  2. Char & Symbols to ASCII Code (in Binary) Converter
  3. ASCII Code to Char Converter