PHP chr() Function
The PHP chr() function returns a character from the specified ASCII value. This function can take ASCII value specified in decimal, octal, or hex values.
- Octal ASCII values start with 0 followed by ASCII value.
- Hex ASCII values start with 0x followed by ASCII value.
This function complements ord() function.
Syntax
chr(ascii)
Parameters
ascii |
Required. Specify ASCII value specified in decimal, octal, or hex values. |
Return Value
Returns a character from the specified ASCII value.
Example: chr() example
In the example below, chr() function returns a character from the specified ASCII value.
<?php echo chr(65)."\n"; echo chr(0101)."\n"; echo chr(0x41)."\n"; ?>
The output of the above code will be:
A A A
Example: overflow behavior
Values outside the valid range (0..255) will be bitwise and'ed with 255, which is equivalent to the following algorithm:
while ($bytevalue < 0) { $bytevalue += 256; } $bytevalue %= 256;
Consider the example below to understand the above discussed concept.
<?php echo chr(-185)."\n"; echo chr(71)."\n"; echo chr(327)."\n"; ?>
The output of the above code will be:
G G G
Example: building a UTF-8 string from individual bytes
Consider one more example where a UTF-8 string is constructed using individual bytes.
<?php $str1 = chr(240) . chr(159) . chr(152) . chr(142); echo $str1; echo "\n"; $str2 = chr(240) . chr(159) . chr(152) . chr(155); echo $str2; ?>
The output of the above code will be:
😎 😛
❮ PHP String Reference