PHP String chr() Function
The PHP String chr() function is used to return a character from the supplied ASCII value. The ASCII value can be given in decimal, octal, or hexadecimal values. Hex values are defined by a leading 0x, and octal values by a leading 0.
Syntax
Below is the syntax of the PHP String chr() function −
string chr ( $ascii)
Parameters
This function accepts $ascii parameter which is the only parameter that this method takes in. There is a valid ASCII value in this parameter. The appropriate character of the ASCII value we supply to the chr() function as the parameter $asciiVal is returned.
Return Value
The chr() function returns the character whose ASCII value we provide.
PHP Version
First introduced in core PHP 4, the chr() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
First we will show you the basic example of the PHP String chr() function when identical characters in multiple ASCII formats are given.
<?php
$num1 = 46;
$num2 = 047;
$num3 = 0x22;
echo "The equivalent character for ASCII 46 in decimal is ";
// Decimal value
echo chr($num1), "\n";
echo "The equivalent character for ASCII 047 in octal is ";
// Octal value
echo chr($num2), "\n";
echo "The equivalent character for ASCII 0x22 in hex is ";
// Hex value
echo chr($num3);
?>
Output
Here is the outcome of the following code −
The equivalent character for ASCII 46 in decimal is . The equivalent character for ASCII 047 in octal is ' The equivalent character for ASCII 0x22 in hex is "
Example 2
In the below PHP code we will try to use the chr() function and get the ASCII values for each value of the array mentioned.
<?php
// Mention array here
$array =[47, 48, 49];
foreach($array as $i) {
echo "The character equivalent of ASCII value of ", $i, " is ";
echo chr($i), "\n";
}
?>
Output
This will generate the below output −
The character equivalent of ASCII value of 47 is / The character equivalent of ASCII value of 48 is 0 The character equivalent of ASCII value of 49 is 1
Example 3
This example uses a random character set to generate an uppercase alphabet string with random ASCII values from 65 to 90.
<?php
// Generate a string of 10 random characters
$randomString = "";
for ($i = 0; $i < 10; $i++) {
// Generate a random ASCII value between 65 and 90
$asciiValue = rand(65, 90);
// Convert ASCII to character using chr()
$randomString .= chr($asciiValue);
}
echo "Randomly generated string: " . $randomString;
?>
Output
This will create the below output −
Randomly generated string: CEBYPWRBLM
Example 4
In the following example, we are using the chr() function to create a triangle of characters based on ASCII values.
<?php
// Define the base ASCII value
$asciiBase = 65;
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j <= $i; $j++) {
// Print the character
echo chr($asciiBase + $j) . " ";
}
echo "\n";
}
?>
Output
Following is the output of the above code −
A A B A B C A B C D A B C D E