Current Location: Home> Latest Articles> PHP chr() Function Explained: How to Generate Characters Using ASCII Codes

PHP chr() Function Explained: How to Generate Characters Using ASCII Codes

gitbox 2025-06-28

Overview of the PHP chr() Function

chr() is one of PHP's built-in functions that converts a numeric parameter into the corresponding ASCII character. The function syntax is as follows:

string chr(int $ascii)

The $ascii parameter represents the ASCII code value to convert, and it must be an integer between 0 and 255.

Return Value of the chr() Function

The return value of the chr() function is the corresponding ASCII character. For example, to convert the number 65 to its corresponding ASCII character, use the following code:

$char = chr(65);
echo $char; // Outputs A

In the code above, the number 65 corresponds to the uppercase letter A in ASCII.

Applications of the chr() Function

Generating a Range of Characters

The chr() function can be used to generate a range of characters. For example, to generate all uppercase letters:

for ($i = 65; $i <= 90; $i++) {
    echo chr($i);
}

In this code, the loop runs 26 times, corresponding to the ASCII values of each uppercase letter.

Generating Random Strings

Since chr() converts numbers to corresponding ASCII characters, it can be used to generate random strings. For example, to generate a random string of length 10:

$string = '';
for ($i = 0; $i < 10; $i++) {
    $random = rand(65, 90); // Generates a random integer between 65 and 90
    $string .= chr($random);
}
echo $string; // Outputs a random string

In this code, the rand() function generates a random integer within a specified range, and the chr() function converts it to a corresponding uppercase letter, which is then appended to form a random string.

Things to Keep in Mind When Using chr()

The chr() function can only convert integers between 0 and 255 into corresponding ASCII characters. Integers outside this range cannot be converted. Additionally, in non-ASCII character encodings, chr() may not properly convert certain special characters.

Conclusion

The chr() function is a commonly used built-in PHP function that converts numbers to corresponding ASCII characters. It is widely used in string manipulation, encoding conversion, and other tasks where character generation or random string creation is required.