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

Rust’s for iterates over an iterator (e.g. arrays, ranges, collections). PHP’s for is C-style; foreach is used for iteration.

Rust

fn main() {
    let a = [10, 20, 30, 40, 50];
    for element in a.iter() {
        println!("Value: {}", element);
    }

    for element in &a {
        println!("Value: {}", element);
    }
}

PHP

<?php
$a = [10, 20, 30, 40, 50];
foreach ($a as $element) {
    echo "Value: $element\n";
}

foreach ($a as $i => $element) {
    echo "Index $i: $element\n";
}

Comparison

  • Rust: for is always iterator-based; no index variable unless you use .enumerate().
  • PHP: foreach for arrays/iterables; for for index-based loops.
  • Rust: Consumes or borrows the iterator; no C-style for (i=0; i<n; i++).
  • PHP: foreach by value or foreach ($a as &$v) for by-reference.

References

What's next

Next: Using ranges with the for loop.

From PHP to Rust — Rust Syntax and Functions