Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Backend Development
1 min read

PHP chr() Function: Converting ASCII Codes to Characters

The article explains PHP's chr() function, detailing its syntax, parameters, and return value, and demonstrates how to convert single ASCII codes, ranges of codes, whole strings, and special characters to their corresponding characters using code examples.

PHP's chr() function converts an ASCII code to its corresponding character.

Basic Syntax

chr(int $ascii) : string

The function takes an integer $ascii representing the ASCII code and returns a one‑character string.

Usage

1. Convert a single ASCII code

Provide a numeric code to obtain the character, e.g.:

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

2. Batch conversion of a range

Loop through a series of codes to output each character:

for ($ascii = 65; $ascii <= 90; $ascii++) {
    $char = chr($ascii);
    echo $char . " ";
}
// outputs: A B C ... Z

3. Convert a whole string

Split a string into characters, get each character's ASCII value with ord(), and convert back with chr():

$str = "Hello";
$chars = str_split($str);
foreach ($chars as $char) {
    $ascii = ord($char);
    $convertedChar = chr($ascii);
    echo $convertedChar . " ";
}
// outputs: H e l l o

4. Special character conversion

Convert codes for spaces, line breaks, etc., for example:

$char = chr(32);
echo $char; // outputs a space

Summary

The chr() function is a simple yet powerful tool in PHP for converting ASCII codes to characters, applicable to single values, ranges, full strings, and special characters.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion