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) : stringThe 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 A2. 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 ... Z3. 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 o4. Special character conversion
Convert codes for spaces, line breaks, etc., for example:
$char = chr(32);
echo $char; // outputs a spaceSummary
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
