Skip to content

Arrays and array<T>

An array is an ordered list of values. Each value has a key. array<int> is an array whose values are all int. Core\Arr has the methods for arrays, such as Core\Arr::count and Core\Arr::sort.

The type array<T>

A list, or a lookup table, whose values all have the same type.

var $ids = [1, 2]; creates an array<int>. Every value you add later must have that type. Write the type yourself, as in array<float> $weights = [2, 1];, when the array starts empty, when its values mix types, or when you will add values of a wider type later.

Keys are strings: $row[3] and $row["3"] are the same entry. An array<Suit, int> has the cases of the enum Suit as its keys instead. Entries keep the order you added them in. An array of arrays is a table or a grouped report.

An array is a value. When you pass it to a function, the function gets its own copy.

Good to know: reading a key that does not exist throws an error. Check first when a key may be missing.

The examples below show a list made with var and one with a written type, then a lookup table, then a grouped report that starts from an empty array. The last one shows how keys are numbered, and that an assigned array is a copy.

Add up a list of prices

<?nvs
// A basket of prices, shown one line at a time and then added up.
// Every value in this list is an `int`, so `var` gives `$prices` the type `array<int>`.
// Every value you add later must be an `int` too.
var $prices = [1299, 450];
$prices[] = 780;
var $total = 0;
foreach ($prices as var $price) {
echo $price, "\n";
$total = $total + $price;
}
echo 'total ', $total, ' over ', Core\Arr::count($prices), " items\n";
// A weight can have a fraction, so this list has the written type `array<float>`.
// With `var`, the list would be `array<int>`, and adding `0.5` would not compile.
array<float> $weights = [2, 1];
$weights[] = 0.5;
// This prints `weight 3.5 kg`.
echo 'weight ', Core\Arr::sum($weights), " kg\n";
Output
1299
450
780
total 2529 over 3 items
weight 3.5 kg

Look up a count by name

<?nvs
// Stock counts kept under the name of the thing being counted.
// The keys are not part of the type. The values are all `int`,
// so `var` gives `$stock` the type `array<int>`.
var $stock = ['apples' => 3, 'pears' => 0];
$stock['figs'] = 7;
// `var $name` is a `string`, because every key is a string.
// `var $count` gets the type of the values, `int`.
foreach ($stock as var $name => var $count) {
echo $name, ': ', $count, "\n";
}
// Reading a name that is not in the array throws an error.
// So check first with `Core\Arr::hasKey`. You can also write the types in a loop.
array<string> $asked = ['pears', 'plums'];
foreach ($asked as string $wanted) {
echo $wanted, Core\Arr::hasKey($stock, $wanted) ? " is stocked\n" : " is not stocked\n";
}
Output
apples: 3
pears: 0
figs: 7
pears is stocked
plums is not stocked

Total a days orders per department

<?nvs
// Totals a day's orders per department and prints the totals as JSON.
// `withServiceFee` gets a copy of `$totals` and changes only that copy.
// So the first line of output shows the original totals.
class Report
{
public static function withServiceFee(array<int> $totals): array<int>
{
foreach ($totals as var $department => var $cents) {
$totals[$department] = $cents + 250;
}
return $totals;
}
}
// An array of arrays suits a grouped report.
// `var` gives `$lines` the type `array<array<int>>`.
var $lines = [
'produce' => [1299, 450],
'bakery' => [780],
];
// An empty array needs a written type. `var $totals = [];` does not compile,
// because the array has no value to take the type from.
array<int> $totals = [];
foreach ($lines as var $department => var $amounts) {
$totals[$department] = Core\Arr::sum($amounts) as int;
}
var $billed = Report::withServiceFee($totals);
echo Core\Json::encode($totals), "\n";
echo Core\Json::encode($billed), "\n";
Output
{"produce":1749,"bakery":780}
{"produce":1999,"bakery":1030}

Keys and copies

<?nvs
// Shows how keys are numbered, and that assigning an array copies it.
array<int> $a = [10, 20];
$a[5] = 50;
// `$a[]` adds a value with the next key after the largest one, here `6`.
$a[] = 60;
// `$a[1]` and `$a["1"]` read the same entry. This prints `2020`.
echo $a[1], $a['1'], "\n";
// `$copy` is a copy. The new key `x` is not added to `$a`, so this prints `4 5`.
array<int> $copy = $a;
$copy['x'] = 1;
echo Core\Arr::count($a), ' ', Core\Arr::count($copy), "\n";
echo Core\Json::encode($a), "\n";
Output
2020
4 5
{"0":10,"1":20,"5":50,"6":60}

Details

An array<T> is an ordered table with string keys and values of the type T. Arrays can contain arrays to any depth, such as array<array<int>>. array<mixed> can contain values of any type.

An int key is the same key as its digits written as a string, so $a[1] and $a["1"] read one entry. The key variable of a foreach loop over an array is always a string.

$a[] = 60; adds a value at the end. Its key is one more than the largest whole-number key, so after $a[5] = 50; the next key is 6.

Every value must have the type T. array<int> $a = [1, "two"]; is the error E0401, and so is $a[] = "x";. Reading a key that does not exist throws a RuntimeError: undefined array key.

Assigning an array to another variable copies it, the same as passing it to a function. A change through one variable is never seen through the other.

An array has no string form: echo $a is the error E0707. Core\Json::encode($a) gives its text. $a + $b with two arrays is the error E0467. Core\Arr::underlay($a, $b) combines them and keeps the value of $a where both have a key.

Building, reading and changing an array

An array is a list of values, or a table where every value has a name.

You write an array as [10, 20] or ["city" => "Graz"]. var $prices = [10, 20] takes the type from the values, so $prices is an array<int>. An empty array, or one whose values have different types, needs the type written: array<int> $prices = []. $prices[] = 30 adds a value at the end. Every key is text, so $prices[8] and $prices["8"] are one entry. Reading a key that is not there throws a RuntimeError. Write $prices["milk"] ?? 0 where a missing key is normal.

Good to know: an array is a value. Assigning, passing or returning it gives a copy, so a change on one side is never seen on the other.

The examples below build a list and a price table, read missing keys and group rows. Example 04 shows keys, spread and nested arrays, 05 destructuring, and 06 does not compile.

A shopping list and a price table

<?nvs
// Builds a shopping list and a table of prices, then reads both back.
// `var` takes the type from the values. Every value is a string, so
// `$basket` is an `array<string>`.
var $basket = ['bread', 'milk'];
// `$basket[] = ...` adds a value at the end. Its key is the next number.
$basket[] = 'coffee';
foreach ($basket as string $position => string $item) {
echo $position, ': ', $item, "\n";
}
// You can also write the type yourself. `[...$basket]` copies every value
// of the list into the new list.
array<string> $withGift = [...$basket, 'flowers'];
echo Core\Arr::count($withGift), " items\n";
// A table gives every value a name you choose. Every value is an `int`, so
// `$prices` is an `array<int>`.
var $prices = ['bread' => 250, 'milk' => 120];
$prices['coffee'] = 890;
echo 'milk costs ', $prices['milk'], " cents\n";
// An empty array has no values to take a type from, so its type is written.
array<int> $discounts = [];
$discounts['milk'] = 20;
echo 'milk costs ', $prices['milk'] - $discounts['milk'], " cents on sale\n";
// Every key is text. `$shelf[8]` and `$shelf["8"]` are the same entry, so a
// number used as a key always finds the value you stored under it.
var $shelf = [8 => 'tea'];
echo $shelf['8'], "\n";
Output
0: bread
1: milk
2: coffee
4 items
milk costs 120 cents
milk costs 100 cents on sale
tea

Keys that may be missing

<?nvs
// Reads settings where a key may be missing. Reading a key that is not
// there throws an error, so this shows the two safe ways to ask for one.
var $settings = ['theme' => 'dark', 'language' => 'de'];
// `??` gives the value on the right when the key is missing.
echo $settings['theme'] ?? 'light', "\n";
echo $settings['timezone'] ?? 'UTC', "\n";
// `isset` tells you whether a key is there.
if (isset($settings['timezone'])) {
echo "a timezone is set\n";
} else {
echo "no timezone is set\n";
}
// `unset` removes one entry. Every other entry keeps its key.
unset($settings['language']);
echo Core\Arr::count($settings), " setting left\n";
// Without a guard the missing key throws a `RuntimeError`, which you can catch.
try {
echo $settings['language'], "\n";
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
dark
UTC
no timezone is set
1 setting left
undefined array key `language`

Grouping orders for a report

<?nvs
// Groups orders by country and adds up what each country spent, the way a
// small report does. Writing into a key that is not there yet creates the
// inner array for you.
// Every order is an `array<string>`, so `var` makes `$orders` an
// `array<array<string>>`.
var $orders = [
['country' => 'AT', 'total' => '42'],
['country' => 'DE', 'total' => '17'],
['country' => 'AT', 'total' => '8'],
];
// The report starts empty, so its type is written out.
array<array<string>> $byCountry = [];
foreach ($orders as string $position => array<string> $order) {
// Destructuring reads two keys of one order into two variables.
['country' => string $country, 'total' => string $total] = $order;
// The first order of a country creates the list under its name.
$byCountry[$country][] = $total;
}
foreach ($byCountry as string $country => array<string> $totals) {
uint $sum = 0;
foreach ($totals as string $index => string $amount) {
$sum = $sum + ($amount as uint);
}
echo $country, ': orders ', Core\Arr::count($totals), ', total ', $sum, "\n";
}
Output
AT: orders 2, total 50
DE: orders 1, total 17

Keys spread and nested arrays

<?nvs
// Shows how keys are numbered, how a spread copies entries, and how a write
// creates an inner array.
array<int> $a = [10, 20];
$a[] = 30;
$a['k'] = 40;
$a[-5] = 50;
// The largest whole-number key is `2`, so this value gets key `3`.
$a[] = 60;
foreach ($a as string $k => int $v) {
echo $k, ':', $v, ' ';
}
echo "\n";
// The spread numbers `-5` again, and keeps `k`. This prints `7 40`.
array<int> $b = [...$a, 'j' => 70];
echo Core\Arr::count($b), ' ', $b['k'], "\n";
// `unset` removes one entry. `$a[0]` and `$a["1"]` still work, so this
// prints `5 30`.
unset($a['k']);
echo Core\Arr::count($a), ' ', $a[0] + $a['1'], "\n";
// This write creates the inner array under `r`.
array<array<int>> $g = [];
$g['r']['c'] = 1;
$g['r'][] = 2;
echo Core\Json::encode($g), "\n";
// `??` covers both keys, so this prints `9`.
echo $g['x']['y'] ?? 9, "\n";
Output
0:10 1:20 2:30 k:40 -5:50 3:60
7 40
5 30
{"r":{"c":1,"0":2}}
9

Destructuring a pair a row and points

<?nvs
// Shows destructuring: reading the entries of an array into variables.
array<int> $pair = [1, 2];
[int $a, int $b] = $pair;
// An empty place skips an entry. `$second` is `2`.
[, int $second] = $pair;
echo $a, ' ', $b, ' ', $second, "\n";
// A key on the left reads that key, in any order.
array<string> $row = ['id' => '7', 'name' => 'ada'];
['name' => string $name, 'id' => string $id] = $row;
echo $id, ' ', $name, "\n";
// A pattern inside a pattern reads an inner array.
array<array<int>> $points = [[1, 2], [3, 4]];
[[int $x1, int $y1], [int $x2, int $y2]] = $points;
echo $x1, $y1, $x2, $y2, "\n";
// A missing key throws a `RuntimeError`.
try {
[int $one, int $two, int $three] = $pair;
echo $three, "\n";
} catch (RuntimeError $e) {
echo $e->message, "\n";
}
Output
1 2 2
7 ada
1234
undefined array key `2`

List does not exist

<?nvs
// Shows that `list(...)` does not exist, so this program does not compile.
// Write `[int $a, int $b] = $pair;` instead.
// proof: compile-error
array<int> $pair = [1, 2];
list(int $a, int $b) = $pair;
Output
error[E0230]: `list(...)` is not supported
--> 06-list-does-not-exist.nvs:7:1
|
7 | list(int $a, int $b) = $pair;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ use `[...]` instead — it is the only destructuring spelling Novis keeps
= help: the elements are written the same way inside `[...]`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

var $a = []; is the error E0414, because an empty array has no values to take a type from. var $a = [1, "x"]; is E0414 too. Its help names the type to write: array<int|string>.

A key is an int, a uint or a string. A float, bool or null key is the error E0434. "08" and "8" are two different keys.

$a[] = 1 uses the largest whole-number key plus one, and a negative key counts too. In an empty array, after $a[-5] = 1; the next key is -4. unset does not number the keys again, so after [10, 20, 30] loses key 1, the next $a[] gets key 3. $a[] can only be written to. Reading it is the error E0481.

[...$a, 30] copies the entries of $a into the new array. A whole-number key, such as "5" or "-3", gets the next number of the new array. Every other key is kept. When two entries have the same key, the later one wins: ["k" => 5, ...$a, "k" => 7] has one k, and it is 7. The values of $a must fit the new array's type. An array<int> spread into an array<string> is the error E0401.

A write into a key that is not there creates every inner array on the way: $g["a"]["b"]["c"] = 1; works on an empty $g. A read does not. $g["a"]["b"] throws a RuntimeError for the first key that is missing: undefined array key a`. ?? and isset test every level, so isset($g["a"]["b"]) is false. isset is also false for a key whose value is null`.

unset($a["k"]) does nothing when the key is not there. It also works on an inner array: unset($g["r"]["0"]).

A function result is not stored anywhere, so A::f()["k"] = 1; is the error E0700. Assign the result to a variable first.

Destructuring reads by key, not by order. [int $a] = $p; reads key "0", wherever it is in $p. Entries that no variable names are skipped, and a missing key throws undefined array key. A positional variable and a "key" => variable can be mixed, and a key can be a variable: [$k => int $v] = $row;.

Each variable in a destructuring needs its type. [$a, $b] = $p; is the error E0101, and [var $a] = $p; is the error E0102. Each type must match the array's value type, or it is the error E0401. The right side must be an array<T>. A mixed or a ?array<int> value is the error E0482. A foreach variable cannot be a destructuring pattern, which is the error E0101. list($a, $b) = $p; is the error E0230.

  • Do write the value type: array<string> $names = [];.
  • Do use Core\Arr methods to count, sort and filter.
  • Do use destructuring to read a fixed number of items, such as a pair.
  • Don’t use an array as a record with fixed fields. A class or an anonymous object gives each field its own type.