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 Courses
php Courses
php Courses
PHP chr() Function: Converting ASCII Codes to Characters

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPchr()character conversion
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.