soundex

soundex(string $string): string

The Soundex phonetic code: names map to a letter-plus-three-digits code so similar-sounding names collide - old but effective fuzzy name retrieval.

C C23

C23
#include <ctype.h>
#include <stdio.h>

/* PHP's variant (Knuth): vowels AND h/w both reset the running code.
   table: 0 for a e h i o u w y, digits per consonant group */
static const char table[26] = {
    0,'1','2','3',0,'1','2',0,0,'2','2','4','5','5',
    0,'1','2','6','2','3',0,'1',0,'2',0,'2'
};

static void soundex(const char *s, char out[5]) {
    int n = 0, last = -1;
    for (; *s && n < 4; s++) {
        int c = toupper((unsigned char)*s);
        if (c < 'A' || c > 'Z') continue;
        if (n == 0) {
            out[n++] = (char)c;
            last = table[c - 'A'];
        } else {
            int code = table[c - 'A'];
            if (code != last) {
                if (code != 0) out[n++] = (char)code;
                last = code;
            }
        }
    }
    while (n < 4) out[n++] = '0';
    out[n] = '\0';
}

int main(void) {
    char r1[5], r2[5], r3[5], r4[5];
    soundex("Robert", r1); soundex("Rupert", r2);
    soundex("Ashcraft", r3); soundex("Tymczak", r4);
    printf("%s %s\n%s %s\n", r1, r2, r3, r4);
    return 0;
}
Output
R163 R163
A226 T522

C++ C++26

C++26
#include <cctype>
#include <iostream>
#include <string>

// PHP's variant (Knuth): vowels AND h/w both reset the running code
static const char table[26] = {
    0,'1','2','3',0,'1','2',0,0,'2','2','4','5','5',
    0,'1','2','6','2','3',0,'1',0,'2',0,'2'
};

static std::string soundex(const std::string& s) {
    std::string out;
    int last = -1;
    for (char raw : s) {
        if (out.size() >= 4) break;
        int c = std::toupper(static_cast<unsigned char>(raw));
        if (c < 'A' || c > 'Z') continue;
        int code = table[c - 'A'];
        if (out.empty()) {
            out.push_back(static_cast<char>(c));
            last = code;
        } else if (code != last) {
            if (code != 0) out.push_back(static_cast<char>(code));
            last = code;
        }
    }
    return out + std::string(4 - out.size(), '0');
}

int main() {
    std::cout << soundex("Robert") << " " << soundex("Rupert") << "\n";
    std::cout << soundex("Ashcraft") << " " << soundex("Tymczak") << "\n";
    return 0;
}
Output
R163 R163
A226 T522

C# v11.0.100

v11.0.100
using System.Text;

class MainClass {
    // PHP's variant (Knuth): vowels AND h/w both reset the running code
    static readonly int[] Table = {
        0,1,2,3,0,1,2,0,0,2,2,4,5,5,
        0,1,2,6,2,3,0,1,0,2,0,2
    };

    static string Soundex(string s) {
        var outp = new StringBuilder();
        int last = -1;
        foreach (char raw in s.ToUpperInvariant()) {
            if (outp.Length >= 4) break;
            if (raw < 'A' || raw > 'Z') continue;
            int code = Table[raw - 'A'];
            if (outp.Length == 0) {
                outp.Append(raw);
                last = code;
            } else if (code != last) {
                if (code != 0) outp.Append((char)('0' + code));
                last = code;
            }
        }
        return outp.ToString().PadRight(4, '0');
    }

    static void Main() {
        System.Console.WriteLine(Soundex("Robert") + " " + Soundex("Rupert"));
        System.Console.WriteLine(Soundex("Ashcraft") + " " + Soundex("Tymczak"));
    }
}
Output
R163 R163
A226 T522

Go v1.27.4

v1.27.4
package main

import "fmt"

// PHP's variant (Knuth): vowels AND h/w both reset the running code
var table = [26]int{0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2}

func soundex(s string) string {
	out := make([]rune, 0, 4)
	last := -1
	for _, raw := range s {
		if len(out) >= 4 {
			break
		}
		c := raw
		if c >= 'a' && c <= 'z' {
			c -= 32
		}
		if c < 'A' || c > 'Z' {
			continue
		}
		code := table[c-'A']
		if len(out) == 0 {
			out = append(out, c)
			last = code
		} else if code != last {
			if code != 0 {
				out = append(out, rune('0'+code))
			}
			last = code
		}
	}
	for len(out) < 4 {
		out = append(out, '0')
	}
	return string(out)
}

func main() {
	fmt.Println(soundex("Robert"), soundex("Rupert"))
	fmt.Println(soundex("Ashcraft"), soundex("Tymczak"))
}
Output
R163 R163
A226 T522

Java v27.0.1

v27.0.1
class Main {
    // PHP's variant (Knuth): vowels AND h/w both reset the running code
    static final int[] TABLE = {
        0,1,2,3,0,1,2,0,0,2,2,4,5,5,
        0,1,2,6,2,3,0,1,0,2,0,2
    };

    static String soundex(String s) {
        StringBuilder out = new StringBuilder();
        int last = -1;
        for (char raw : s.toUpperCase().toCharArray()) {
            if (out.length() >= 4) break;
            if (raw < 'A' || raw > 'Z') continue;
            int code = TABLE[raw - 'A'];
            if (out.length() == 0) {
                out.append(raw);
                last = code;
            } else if (code != last) {
                if (code != 0) out.append((char) ('0' + code));
                last = code;
            }
        }
        while (out.length() < 4) out.append('0');
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(soundex("Robert") + " " + soundex("Rupert"));
        System.out.println(soundex("Ashcraft") + " " + soundex("Tymczak"));
    }
}
Output
R163 R163
A226 T522

JavaScript v26.13.1

v26.13.1
// PHP's variant (Knuth): vowels AND h/w both reset the running code
const TABLE = [0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2];

function soundex(s) {
  let out = "";
  let last = -1;
  for (const raw of s.toUpperCase()) {
    if (out.length >= 4) break;
    if (raw < "A" || raw > "Z") continue;
    const code = TABLE[raw.charCodeAt(0) - 65];
    if (out.length === 0) {
      out += raw;
      last = code;
    } else if (code !== last) {
      if (code !== 0) out += String(code);
      last = code;
    }
  }
  return (out + "000").slice(0, 4);
}

console.log(soundex("Robert"), soundex("Rupert"));
console.log(soundex("Ashcraft"), soundex("Tymczak"));
Output
R163 R163
A226 T522

PHP v8.6.0

v8.6.0
// PHP uses the Knuth variant: vowels AND h/w both reset the running code
// (NARA would give Ashcraft A261 - PHP says A226, the sc are NOT folded)
echo soundex("Robert"), " ", soundex("Rupert"), "\n";   // same code: R163
echo soundex("Ashcraft"), " ", soundex("Ashcroft"), "\n"; // A226 A226
echo soundex("Tymczak"), " ", soundex("Honeyman"), "\n"; // T522 H555
Output
R163 R163
A226 A226
T522 H555

Python v3.15.2

v3.15.2
# PHP's variant (Knuth): vowels AND h/w both reset the running code
TABLE = [0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5,
         0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2]


def soundex(s):
    out = ""
    last = -1
    for raw in s.upper():
        if len(out) >= 4:
            break
        if not ("A" <= raw <= "Z"):
            continue
        code = TABLE[ord(raw) - 65]
        if not out:
            out += raw
            last = code
        elif code != last:
            if code != 0:
                out += str(code)
            last = code
    return (out + "000")[:4]


print(soundex("Robert"), soundex("Rupert"))
print(soundex("Ashcraft"), soundex("Tymczak"))
Output
R163 R163
A226 T522

Rust v1.99.1

v1.99.1
// PHP's variant (Knuth): vowels AND h/w both reset the running code
const TABLE: [u8; 26] = [
    0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0, 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2,
];

fn soundex(s: &str) -> String {
    let mut out = String::new();
    let mut last: i32 = -1;
    for raw in s.to_uppercase().chars() {
        if out.len() >= 4 {
            break;
        }
        if !raw.is_ascii_uppercase() {
            continue;
        }
        let code = TABLE[(raw as usize) - 'A' as usize] as i32;
        if out.is_empty() {
            out.push(raw);
            last = code;
        } else if code != last {
            if code != 0 {
                out.push((b'0' + code as u8) as char);
            }
            last = code;
        }
    }
    format!("{:0<4}", out)
}

fn main() {
    println!("{} {}", soundex("Robert"), soundex("Rupert"));
    println!("{} {}", soundex("Ashcraft"), soundex("Tymczak"));
}
Output
R163 R163
A226 T522

TypeScript v26.13.1

v26.13.1
// PHP's variant (Knuth): vowels AND h/w both reset the running code
const TABLE: number[] = [0,1,2,3,0,1,2,0,0,2,2,4,5,5,0,1,2,6,2,3,0,1,0,2,0,2];

function soundex(s: string): string {
  let out = "";
  let last = -1;
  for (const raw of s.toUpperCase()) {
    if (out.length >= 4) break;
    if (raw < "A" || raw > "Z") continue;
    const code = TABLE[raw.charCodeAt(0) - 65];
    if (out.length === 0) {
      out += raw;
      last = code;
    } else if (code !== last) {
      if (code !== 0) out += String(code);
      last = code;
    }
  }
  return (out + "000").slice(0, 4);
}

console.log(soundex("Robert"), soundex("Rupert"));
console.log(soundex("Ashcraft"), soundex("Tymczak"));
Output
R163 R163
A226 T522

Language differences

C: a 26-entry table + hand-written state machine (example); pass unsigned char to toupper and leave a \0 slot in out (5 bytes); non-letters are skipped entirely without updating last - the key detail of the original Knuth implementation.

C++: a std::string state machine (example); break as soon as 4 chars are filled (PHP source behavior: _small < 4 is the loop condition, characters after the fourth cannot affect the result).

C#: StringBuilder + PadRight (example); ToUpperInvariant() over ToUpper() - the code only cares about ASCII letters, locale independence is safer.

Go: rune scan + the - 32 uppercase offset (example); no built-in soundex - MySQL's SOUNDEX() SQL function is the most common substitute path in Go services.

Java: toCharArray traversal (example); Apache Commons Codec ships a Soundex class but that is the NARA standard version - it gives Ashcraft A261, unlike this example (which replicates PHP)! Choose the algorithm deliberately when cross-checking libraries.

JavaScript: a string state machine (example); charCodeAt(0) - 65 is the standard A-to-0 trick; (out + "000").slice(0, 4) pads and truncates in one move.

PHP: the source is the Knuth TAOCP vol 3 variant (all four cases verified on this machine: Robert/Rupert=R163, Ashcraft/Ashcroft=A226, Tymczak=T522, Honeyman=H555); the FAMOUS divergence from the NARA US-Census standard: NARA gives Ashcraft A261 (s and c separated by h are not folded) while PHP gives A226 (h/w reset like vowels) - a database SOUNDEX() and PHP soundex() may disagree; always cross-check across systems; an empty string returns an empty string, not four characters.

Python: hand-written implementation (example); the standard library has no soundex - fuzzy/jellyfish on PyPI exist but are mostly NARA versions; a self-implemented Knuth variant is the safest way to match PHP.

Rust: format!("{:0<4}") pads left with zeros (example); no built-in soundex and crates likewise lean NARA; is_ascii_uppercase reads better than range comparisons.

TypeScript: same as JS (example); TABLE: number[] typed explicitly; exporting a NARA version alongside is wise - the two variants coexisting is the real state of the soundex ecosystem.