What is the chr() function in PHP?

Overview

The chr() function creates a one-character string using any of the single-byte encoding schemes such as ASCII, ISO-8859, or Windows 1252. It does this by passing the position of the desired character in the encoding’s mapping table.

The chr() function does not compute any string encoding. It, therefore, returns the single-character string as just a string with no encoding information attached. Because of this, we cannot pass the Unicode codepoint value expecting it to generate a string in a multibyte encoding like UTF-8 or UTF-16.

In simple terms, the chr() method is used to create a single character string value using its Unicode byte value. These values range from 0 to 255 representation.

Syntax

chr($codepoint)

Parameter

  • $codepoint: This is the Unicode byte value that will be mapped to the encoding mapping table to get its character equivalent.

Code

The code snippet below contains different use case instances of the chr() method:

<?php
$var1 = [32,69,84,100,101,104,105,111,112,114,115];
$var2 = [98,99,101,105,110,111,114,116,117];
$var3 = [32,97,100,104,111,114,115,116,117,121];
//use a for loop on $var1
for( $i = 0; $i <= sizeof($var1); $i++){
echo chr($var1[$i]);
}
echo "\n";
//use the foreach loop on array var2 and var3.
foreach($var2 as $var){
echo chr($var);
}
echo "\n";
foreach($var3 as $var){
echo chr($var);
}

Explanation

  • Line 1: We start the PHP code block.

  • Lines 3–5: We declare an array of byte values that will be converted into their character equivalent.

  • Line 8–10: We use the for loop to go over the $var1 array. We do this to get the characters represented by the byte value it contains using the chr() function on line 9.

  • Lines 14, 15, and 16: We use the foreach loop to go over the $var2 array. We do this to get the characters represented by the byte value it contains using the chr() function on line 15. We also did the same in lines 20 to 22 on $var3.

Free Resources