Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.
In Rust, arrays are fixed-length and all elements share the same type. PHP arrays are dynamic and can mix types and key types.
Can you add more elements to a Rust array?
Not if you mean [T; N]. A Rust array has a length baked into its type: N never changes. You cannot append, push, or resize it in place, there is no “make this array one slot longer” on the same value.
What you can do on a mut array is replace elements at existing indices (e.g. a[2] = 99). The number of slots is still N.
If you need a collection that grows or shrinks at runtime (like PHP’s $a[] = 6;), use Vec<T> (or another growable type), not a fixed [T; N]. Slices &[T] borrow some contiguous elements but don’t own a growable buffer either, they’re a view over an array or Vec.
Summary
Fixed array [T; N] |
Vec<T> |
|
|---|---|---|
| Length in the type? | Yes (N is fixed) |
No (length at runtime) |
| Add/remove elements? | No | Yes (e.g. .push(), .pop()) |
| Change element values? | Yes, with mut |
Yes, with mut |
Rust
fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
let same: [i32; 3] = [42; 3]; // [42, 42, 42]
println!("First: {}", a[0]);
println!("Length: {}", a.len());
println!("same (repeat syntax): {:?}", same);
// Bounds checked at runtime
// let x = a[10]; // Panic: index out of bounds
}
- Type is
[T; N]: element type and length. - Stored on the stack (for reasonable sizes).
- Use
Vec<T>for dynamic length.
PHP
<?php
$a = [1, 2, 3, 4, 5];
$same = array_fill(0, 3, 42); // [42, 42, 42]
echo "First: " . $a[0] . "\n";
echo "Length: " . count($a) . "\n";
// Can grow
$a[] = 6;
// Can mix types
$mixed = [1, "hello", 3.14, true];
PHP arrays are ordered maps; numeric keys make them work like lists.
Comparison
- Rust: Fixed length, single type. Use
Vecfor growable. Stored on stack when small. - PHP: Dynamic length, any types. Supports int and string keys.
References
What's next
Next: Slices.
From PHP to Rust — Rust Syntax and Functions