How to Use the PHP chr() Function with Examples
June 19, 2024 ⚊ 2 Min read ⚊ PHPThe chr()
function in PHP is used to return a character from a specified ASCII value. ASCII (American Standard Code for Information Interchange) values range from 0 to 255, where each value corresponds to a specific character.
Example Usage
Here’s a simple example to demonstrate how to use the chr()
function:
<?php
// ASCII value for 'A' is 65
$char = chr(65);
echo $char; // Outputs: A
// ASCII value for 'a' is 97
$char = chr(97);
echo $char; // Outputs: a
// ASCII value for '0' is 48
$char = chr(48);
echo $char; // Outputs: 0
// ASCII value for a newline character is 10
$char = chr(10);
echo $char; // Outputs a newline
?>
Practical Example
In a practical scenario, you might use the chr()
function to generate characters based on their ASCII values, for instance, creating a string from ASCII values stored in an array:
<?php
$asciiValues = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100];
$string = '';
foreach ($asciiValues as $value) {
$string .= chr($value);
}
echo $string; // Outputs: Hello World
?>
Handling Out of Range Values
If you provide a value outside the 0-255 range, PHP will interpret it modulo 256. Here’s how it works:
<?php
$char = chr(256);
echo $char; // Outputs: \0 (same as chr(0))
$char = chr(257);
echo $char; // Outputs: \1 (same as chr(1))
?>
Combining with ord()
Function
The ord()
function is the inverse of chr()
. It returns the ASCII value of the first character of a string. These functions can be combined:
<?php
$originalChar = 'A';
$asciiValue = ord($originalChar);
$char = chr($asciiValue);
echo $char; // Outputs: A
?>
Conclusion
The chr()
function is a simple yet powerful tool in PHP for converting ASCII values to their corresponding characters. It can be especially useful when dealing with low-level data processing or when you need to manipulate text based on ASCII values.