PHP chr() Function: Generating Characters from ASCII Codes
What is the PHP chr() Function?
The chr() function in PHP converts an ASCII value (an integer) into its corresponding character. It is useful for generating characters dynamically based on their ASCII codes.
Syntax
string chr(int $ascii);
Parameter:
$ascii: An integer representing the ASCII code of the character to be returned. Valid values range from 0 to 255.
Return Value:
Returns the character corresponding to the ASCII value.
Basic Example of chr()
<?php
echo chr(65); // Output: A
echo chr(97); // Output: a
?>
ey Use Cases
Generate Alphabetic Characters: Use ASCII codes for letters, where A-Z ranges from 65-90 and a-z ranges from 97-122.
Special Characters: ASCII codes can represent non-printable characters, such as tab (9), newline (10), or space (32).
Advanced Examples
1. Generating a Range of Characters
<?php
for ($i = 65; $i <= 90; $i++) {
echo chr($i) . " "; // Output: A B C ... Z
}
?>