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

  1. Generate Alphabetic Characters:
    Use ASCII codes for letters, where A-Z ranges from 65-90 and a-z ranges from 97-122.

  2. 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
}
?>

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

CharacterASCII CodeUsage
A65Uppercase letters
a97Lowercase letters
048Digits
Space32Whitespace
Tab9Indentation
Newline10Line 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()

FunctionPurposeExample
chr()Converts ASCII to characterchr(65) // 'A'
ord()Converts character to ASCIIord('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
?>
2. Creating ASCII Art
<?php
for ($i = 65; $i <= 69; $i++) {
    echo str_repeat(chr($i), $i - 64) . "\n";
}
?>
 

Output:

A
BB
CCC
DDDD
EEEEE