PHP Tutorial

Letters to Numbers in PHP — ord() and chr() Guide

AlphaCoder Team|May 23, 2026|10 min read

PHP's ord() and chr() functions provide the simplest path for converting between letters and numbers. Whether you are building a WordPress plugin, processing form data, or implementing a cipher algorithm, PHP handles letter-number conversion efficiently. To convert letters instantly without writing code, use our letters to numbers converter.

The Basics: ord() and chr()

The ord() function returns the ASCII value of the first character in a string. The chr() function does the reverse, converting a number back to its character.

<?php
// Letter to ASCII value
echo ord('A');   // 65
echo ord('Z');   // 90
echo ord('a');   // 97

// Letter to alphabet position (A=1, Z=26)
echo ord('A') - 64;   // 1
echo ord('M') - 64;   // 13
echo ord('Z') - 64;   // 26

// For lowercase, convert to uppercase first
echo ord(strtoupper('m')) - 64;   // 13

// Number to letter
echo chr(65);          // A
echo chr(90);          // Z
echo chr(13 + 64);     // M (position 13)
echo chr(13 + 96);     // m (lowercase)
?>

Converting Full Strings

Using str_split() and array_map()

<?php
function encodeA1Z26(string $text, string $sep = '-'): string {
    $chars = str_split(strtoupper($text));
    $positions = array_map(function($c) {
        return ctype_alpha($c) ? ord($c) - 64 : null;
    }, $chars);

    return implode($sep, array_filter($positions, 'is_int'));
}

echo encodeA1Z26('Hello');        // 8-5-12-12-15
echo encodeA1Z26('Hello', ',');   // 8,5,12,12,15
echo encodeA1Z26('PHP 8.3!');     // 16-8-16
?>

Arrow Functions (PHP 7.4+)

<?php
// Cleaner with arrow functions
function encodeA1Z26Short(string $text, string $sep = '-'): string {
    $chars = str_split(strtoupper($text));
    $nums = array_filter(
        array_map(fn($c) => ctype_alpha($c) ? ord($c) - 64 : null, $chars),
        fn($v) => $v !== null
    );
    return implode($sep, $nums);
}

// Word value (sum of positions)
function wordValue(string $text): int {
    return array_sum(
        array_map(
            fn($c) => ctype_alpha($c) ? ord(strtoupper($c)) - 64 : 0,
            str_split($text)
        )
    );
}

echo wordValue('PHP');     // 42 (16+8+16+2 → wait: P=16, H=8, P=16 = 40 actually!)
// Correction: P=16, H=8, P=16 → 40
echo wordValue('Hello');   // 52
?>

Decoding Numbers Back to Text

<?php
function decodeA1Z26(string $encoded, string $sep = '-'): string {
    $parts = explode($sep, $encoded);
    $letters = array_map(function($n) {
        $num = intval(trim($n));
        return ($num >= 1 && $num <= 26) ? chr($num + 64) : '';
    }, $parts);
    return implode('', $letters);
}

echo decodeA1Z26('8-5-12-12-15');   // HELLO
echo decodeA1Z26('16,8,16', ',');   // PHP
?>

You can verify these conversions with our ASCII converter tool, which shows both ASCII codes and alphabet positions.

Preserving Word Boundaries

<?php
function encodeWithWords(
    string $text,
    string $sep = '-',
    string $wordSep = ' / '
): string {
    $words = preg_split('/\s+/', $text);
    $encoded = array_map(
        fn($word) => encodeA1Z26($word, $sep),
        $words
    );
    return implode($wordSep, array_filter($encoded));
}

echo encodeWithWords('Hello World');
// Output: 8-5-12-12-15 / 23-15-18-12-4
?>

Unicode Support: mb_ord() and mb_chr()

For international characters, PHP provides multibyte equivalents. Our Unicode converter handles these characters as well.

<?php
// mb_ord() handles multibyte characters (PHP 7.2+)
echo mb_ord('A');         // 65 (same as ord for ASCII)
echo mb_ord('Z');         // 90

// Where mb_ord shines: Unicode characters
echo mb_ord('\u00C9');    // 201 (É - E with acute)
echo mb_ord('\u4E2D');    // 20013 (中 - Chinese character)

// mb_chr() reverses the conversion
echo mb_chr(65);          // A
echo mb_chr(201);         // É
echo mb_chr(20013);       // 中

// For A-Z letter conversion, ord() is sufficient and faster
// Use mb_ord() only when handling non-ASCII characters
?>

WordPress Shortcode Plugin Example

Here is a complete WordPress shortcode plugin that lets users convert text to numbers in any post or page:

<?php
/**
 * Plugin Name: A1Z26 Converter Shortcode
 * Description: Adds [a1z26] shortcode for letter-to-number conversion
 * Version: 1.0.0
 */

// Register shortcode
add_shortcode('a1z26', function($atts, $content = '') {
    $atts = shortcode_atts([
        'separator' => '-',
        'mode'      => 'encode',  // encode or decode
    ], $atts);

    $text = sanitize_text_field($content);

    if ($atts['mode'] === 'decode') {
        $result = a1z26_decode($text, $atts['separator']);
    } else {
        $result = a1z26_encode($text, $atts['separator']);
    }

    return '<span class="a1z26-result">'
        . esc_html($result) . '</span>';
});

function a1z26_encode(string $text, string $sep): string {
    $chars = str_split(strtoupper($text));
    $nums = [];
    foreach ($chars as $c) {
        if (ctype_alpha($c)) {
            $nums[] = ord($c) - 64;
        }
    }
    return implode($sep, $nums);
}

function a1z26_decode(string $encoded, string $sep): string {
    $parts = explode($sep, $encoded);
    $result = '';
    foreach ($parts as $p) {
        $n = intval(trim($p));
        if ($n >= 1 && $n <= 26) {
            $result .= chr($n + 64);
        }
    }
    return $result;
}
?>

Usage in WordPress posts: [a1z26]Hello World[/a1z26]outputs "8-5-12-12-15-23-15-18-12-4".

Processing Form Input Safely

<?php
// Handle form submission with validation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = $_POST['text'] ?? '';

    // Sanitize: strip tags, trim whitespace
    $clean = trim(strip_tags($input));

    // Validate: only allow letters and spaces
    if (!preg_match('/^[a-zA-Z\s]+$/', $clean)) {
        $error = 'Please enter only letters and spaces.';
    } else {
        $encoded = encodeA1Z26($clean);
        $value = wordValue($clean);
    }
}
?>

Performance: Batch Processing Large Texts

<?php
// For large files, process line by line to save memory
function encodeFile(string $inputPath, string $outputPath): void {
    $in = fopen($inputPath, 'r');
    $out = fopen($outputPath, 'w');

    while (($line = fgets($in)) !== false) {
        $encoded = encodeWithWords(trim($line));
        fwrite($out, $encoded . PHP_EOL);
    }

    fclose($in);
    fclose($out);
}

// Pre-built lookup array for maximum speed
$POSITIONS = [];
for ($i = 0; $i < 26; $i++) {
    $POSITIONS[chr(65 + $i)] = $i + 1;  // A=1 ... Z=26
    $POSITIONS[chr(97 + $i)] = $i + 1;  // a=1 ... z=26
}

// O(1) lookup instead of ord() arithmetic
function fastPosition(string $c): int {
    global $POSITIONS;
    return $POSITIONS[$c] ?? -1;
}
?>

Convert instantly: Try our ASCII Converter to see ASCII values, or explore full encoding with the A1Z26 Cipher tool.

Try it now →

Frequently Asked Questions

How do I convert a letter to a number in PHP?

Use ord('A') to get 65 (ASCII value), or ord('A') - 64 to get 1 (alphabet position). Always use strtoupper() first to normalize case. The ord() function only reads the first character of a string.

What is the difference between ord() and mb_ord() in PHP?

ord() handles single-byte ASCII characters only, while mb_ord() correctly processes multibyte Unicode characters. For English A-Z letters, both return identical results. Use mb_ord() when your application handles international characters like accented vowels or CJK text.

How do I convert an entire string to numbers in PHP?

Use str_split() with array_map() and implode(). Split the string into individual characters, map each letter to its position using ord(strtoupper($c)) - 64, filter out non-letters with ctype_alpha(), and join with your chosen separator.

Related Articles