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, whereA-Z
ranges from65-90
anda-z
ranges from97-122
.Special Characters:
ASCII codes can represent non-printable characters, such astab
(9),newline
(10), orspace
(32).
Advanced Examples
1. Generating a Range of Characters
<?php
for ($i = 65; $i <= 90; $i++) {
echo chr($i) . " "; // Output: A B C ... Z
}
?>
2. Creating Special Characters
<?php
echo "Tab: '" . chr(9) . "'\n";
echo "Newline: '" . chr(10) . "'\n";
?>
3. Dynamic Character Generation
<?php
function generateRandomChar() {
return chr(rand(65, 90)); // Random uppercase letter
}
echo generateRandomChar(); // Example output: X
?>
4. Decoding Hexadecimal ASCII Codes
<?php
$hex = 0x41; // Hexadecimal for 'A'
echo chr($hex); // Output: A
?>
Common ASCII Values
Character | ASCII Code | Usage |
---|---|---|
A | 65 | Uppercase letters |
a | 97 | Lowercase letters |
0 | 48 | Digits |
Space | 32 | Whitespace |
Tab | 9 | Indentation |
Newline | 10 | Line breaks |
Best Practices
Validate Input Range:
Ensure the input value is between 0 and 255 to avoid unexpected results.Use Readable Constants:
Instead of hardcoding ASCII values, consider using descriptive constants or comments for clarity.
echo chr(65); // A
Use with Unicode Caution:
The chr()
function is limited to the first 256 characters. For Unicode, use mb_chr()
in PHP 7.2+.
Difference Between chr()
and ord()
Function | Purpose | Example |
---|---|---|
chr() | Converts ASCII to character | chr(65) // 'A' |
ord() | Converts character to ASCII | ord('A') // 65 |
Common Mistakes
Out-of-Range Values:
Providing an ASCII value greater than 255 may result in unexpected behavior.
echo chr(300); // Undefined result
Incorrect Range for Characters:
Using a random number generator with an invalid range can produce errors.
Use Cases
1. Password Generators
<?php
function generatePassword($length) {
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= chr(rand(33, 126)); // Printable ASCII range
}
return $password;
}
echo generatePassword(8); // Example: @G4kP#2H
?>
<?php
for ($i = 65; $i <= 69; $i++) {
echo str_repeat(chr($i), $i - 64) . "\n";
}
?>
Output:
A
BB
CCC
DDDD
EEEEE