Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo chr(65);     // A
echo ord("a");    // 97

Try it

PHP Codes and letters

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.

PHP A Caesar cipher and UTF-8

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

PHP
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}" or mb_chr(233).
  • Deprecations in PHP 8.5. chr() with a value outside 0-255 (it used to wrap modulo 256, so chr(321) was chr(65)) and ord() with an empty or multi-byte string (ord("") was 0, ord("hello") was 104) now emit a deprecation notice. Pass $str[0] to ord() and keep the number in range, for example with % 256.
  • Iterating over characters. str_split() splits into bytes, so for UTF-8 loop with mb_str_split() and call mb_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 for A in double quotes, resolved at compile time without calling chr().
  • Case change by arithmetic works for ASCII letters only. Use strtoupper() or mb_strtoupper() for real text.