Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Rust's char is a 32-bit Unicode scalar value (one character). PHP uses strings; a "character" is typically a single-byte or multi-byte substring.

Rust

fn main() {
    let letter: char = 'R';
    let emoji: char = '🦀';
    let accented: char = 'é';
    let newline: char = '\n';

    println!(
        "letter={:?}, emoji={:?}, accented={:?}, newline={:?}",
        letter, emoji, accented, newline
    );

    // Iterate over chars in a string
    for c in "hello".chars() {
        println!("{}", c);
    }

    // char is 4 bytes (Unicode scalar value)
    println!("{}", std::mem::size_of::<char>());  // 4
}
  • char is always a valid Unicode scalar value.
  • Single quotes for char, double quotes for str.
  • Emoji and other Unicode code points are valid char values.

PHP

<?php
// PHP has no char type, use single-character strings
$letter = 'R';
$emoji = '🦀';
$accented = 'é';

// mb_strlen for multibyte strings
echo mb_strlen($emoji);  // 1 (one Unicode codepoint)
echo strlen($emoji);     // 4 (bytes in UTF-8)

// Iterate as bytes or use mb_* for characters
foreach (mb_str_split('hello') as $c) {
    echo $c;
}

In PHP, "characters" are one-character strings. Use mb_* for proper Unicode handling.

Comparison

  • Rust: char is 4 bytes, one Unicode scalar value. Literal: 'a'.
  • PHP: No char type; use single-character strings. Use mb_* for Unicode.

References

What's next

Next: Compound types.

From PHP to Rust