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

Loops can be nested to iterate over multidimensional data. Same idea in both languages.

Rust

fn main() {
    let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
    for row in matrix.iter() {
        for element in row.iter() {
            print!("{} ", element);
        }
        println!();
    }
}

PHP

<?php
$matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
foreach ($matrix as $row) {
    foreach ($row as $element) {
        echo "$element ";
    }
    echo "\n";
}

Comparison

  • Rust: Use .iter() or &matrix to borrow; nested for on each dimension.
  • PHP: foreach naturally iterates nested arrays.
  • Rust: Use break 'label to exit outer loops from inner loops.
  • PHP: break 2 to exit two levels.

References

What's next

Next: Pattern matching with match.

From PHP to Rust — Rust Syntax and Functions