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

Rust ranges provide start..end (exclusive) and start..=end (inclusive). PHP uses C-style for or range() for similar iteration.

Rust

fn main() {
    for n in 1..5 {
        println!("{}", n);  // 1, 2, 3, 4
    }
    for n in 1..=5 {
        println!("{}", n);  // 1, 2, 3, 4, 5
    }
}

PHP

<?php
foreach (range(1, 4) as $n) {
    echo "$n\n";  // 1, 2, 3, 4
}
foreach (range(1, 5) as $n) {
    echo "$n\n";  // 1, 2, 3, 4, 5
}

// Or C-style for
for ($i = 1; $i < 5; $i++) {
    echo "$i\n";
}

Comparison

  • Rust: a..b excludes b; a..=b includes b; both produce iterators.
  • PHP: range(1, 5) is inclusive; creates an array.
  • Rust: Ranges are lazy iterators; no array allocation.
  • PHP: range() allocates an array; use a for loop for memory efficiency on large ranges.

References

What's next

Next: Nesting loops.

From PHP to Rust — Rust Syntax and Functions