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
<code>chr(int $ascii) : string</code>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.:
<code>$char = chr(65);
echo $char; // outputs A</code>2. Batch conversion of a range
Loop through a series of codes to output each character:
<code>for ($ascii = 65; $ascii <= 90; $ascii++) {
$char = chr($ascii);
echo $char . " ";
}
// outputs: A B C ... Z</code>3. Convert a whole string
Split a string into characters, get each character's ASCII value with ord() , and convert back with chr() :
<code>$str = "Hello";
$chars = str_split($str);
foreach ($chars as $char) {
$ascii = ord($char);
$convertedChar = chr($ascii);
echo $convertedChar . " ";
}
// outputs: H e l l o</code>4. Special character conversion
Convert codes for spaces, line breaks, etc., for example:
<code>$char = chr(32);
echo $char; // outputs a space</code>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.
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.