Accessing Arrays
Dot notation
ZYMBA
$person = [name: "Alice", age: 30];
echo $person.name; // "Alice"
echo $person.age; // 30
Bracket notation
ZYMBA
$colors = ["red", "green", "blue"];
echo $colors[0]; // "red"
echo $colors[2]; // "blue"
// Dynamic key
$key = "name";
echo $person[$key]; // "Alice"
First and last
ZYMBA
$items = [10, 20, 30];
echo @Array.firstValue($items); // 10
echo @Array.lastValue($items); // 30
echo @Array.firstKey($items); // 0
echo @Array.lastKey($items); // 2
Head and tail (Lisp-style)
head returns the first element. tail returns all elements except the first:
ZYMBA
$items = [10, 20, 30, 40, 50];
$first = @Array.head($items); // 10
$rest = @Array.tail($items); // [20, 30, 40, 50]
Access by position
ZYMBA
$items = [a: 10, b: 20, c: 30];
echo @Array.keyAt($items, 1); // "b" (key at position 1)
echo @Array.valueAt($items, "b"); // 20 (value at key "b")
Iteration
for-as loop
ZYMBA
// Values only
$colors = ["red", "green", "blue"];
for ($colors as $color) {
echo "$color ";
}
// red green blue
// Key-value pairs
$prices = [apple: 1.50, banana: 0.75, cherry: 3.00];
for ($prices as $fruit: $price) {
echo "$fruit: $price\n";
}
@Array.forEach
ZYMBA
$items = ["a", "b", "c"];
@Array.forEach($items, function($value, $key) {
echo "$key=$value ";
});
// 0=a 1=b 2=c
Destructuring in loops
ZYMBA
$rows = [
[name: "Alice", age: 30],
[name: "Bob", age: 25]
];
for ($rows as [$name, $age]) {
echo "$name is $age\n";
}
Key and value extraction
ZYMBA
$person = [name: "Alice", age: 30, city: "NYC"];
$keys = @Array.listKeys($person);
// ["name", "age", "city"]
$values = @Array.listValues($person);
// ["Alice", 30, "NYC"]
// Extract a column from a multidimensional array
$users = [
[name: "Alice", age: 30],
[name: "Bob", age: 25]
];
$names = @Array.listValues($users, "name");
// ["Alice", "Bob"]