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

A tuple groups a fixed number of values of (possibly different) types. PHP does not have tuples; you use indexed arrays or short arrays instead.

Rust

fn main() {
    let point: (i32, i32) = (10, 20);
    let mixed: (i32, f64, char) = (500, 6.4, 'R');

    // Destructuring
    let (x, y) = point;
    println!("x={}, y={}", x, y);

    // Dot notation by index
    let first = mixed.0;
    let second = mixed.1;
    println!("first={}, second={}", first, second);

    // Return multiple values
    let (sum, product) = calculate(10, 5);
    println!("sum={}, product={}", sum, product);
}

fn calculate(a: i32, b: i32) -> (i32, i32) {
    (a + b, a * b)
}

Tuples are fixed-size and often used to return multiple values from functions.

PHP

PHP uses indexed arrays to simulate tuples:

<?php
$point = [10, 20];
$mixed = [500, 6.4, 'R'];

// List destructuring (PHP 7.1+)
[$x, $y] = $point;
echo "x=$x, y=$y\n";

// Index access
$first = $mixed[0];
$second = $mixed[1];

// Return multiple values
[$sum, $product] = calculate(10, 5);
echo "sum=$sum, product=$product\n";

function calculate(int $a, int $b): array {
    return [$a + $b, $a * $b];
}

PHP arrays are dynamic and can change length; Rust tuples cannot.

Comparison

  • Rust: (a, b, c), fixed size, mixed types. Destructure with let (a, b) = t. Access with t.0, t.1.
  • PHP: Use [a, b, c]; can destructure with [$a, $b] = $arr. Arrays are dynamic.

References

What's next

Next: Arrays.

From PHP to Rust — Rust Syntax and Functions