PHP Reference ยท String Functions
PHP chr() and ord() functions
Reference for PHP chr() and ord(): convert between a byte value and a one-byte string, ASCII codes, wrap-around, UTF-8 pitfalls and the mb_chr() alternatives.
chr() takes a number and returns a one-byte string with that byte value. ord() does the reverse: it returns the byte value (0 to 255) of the first byte of a string. Together they let you work with ASCII codes, shift letters for simple ciphers, build binary data and loop over the alphabet.
Both functions work on bytes, not characters. For plain ASCII that is the same thing. For UTF-8 text, a single character such as รฉ or โฌ takes two or three bytes, so ord() reports only the first byte. Use mb_chr() and mb_ord() when you want Unicode code points.
<?php echo chr(65); // A echo ord("a"); // 97
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
chr(int $codepoint): string ord(string $character): int
| Name | Description |
|---|---|
$codepoint |
The byte value, 0 to 255. Other values still wrap around modulo 256, but this is deprecated since PHP 8.5. |
$character |
A string of exactly one byte. A longer string still uses its first byte and an empty string gives 0, but both are deprecated since PHP 8.5. |
Return value: chr() returns a string of length 1. ord() returns an integer from 0 to 255.
Usage notes
- Bytes, not characters.
chr(233)is a single byte that is not valid UTF-8 on its own. To getรฉ, use"รฉ"directly,"\u{E9}"ormb_chr(233). - Deprecations in PHP 8.5.
chr()with a value outside 0-255 (it used to wrap modulo 256, sochr(321)waschr(65)) andord()with an empty or multi-byte string (ord("")was0,ord("hello")was104) now emit a deprecation notice. Pass$str[0]toord()and keep the number in range, for example with% 256. - Iterating over characters.
str_split()splits into bytes, so for UTF-8 loop withmb_str_split()and callmb_ord()on each piece. - Hex and binary. To see the bytes of a string use
bin2hex();dechex(ord($c))gives one byte. - Escapes.
"\x41"and"\101"are string escapes forAin double quotes, resolved at compile time without callingchr(). - Case change by arithmetic works for ASCII letters only. Use
strtoupper()ormb_strtoupper()for real text.