Skip to content

2. Arrays and loops

From this step on, the Tour builds a small task list. The program keeps the titles of the tasks in an array:

<?nvs
// This program keeps a list of tasks in an array and prints each one.
class Tasks
{
public static function report(array<string> $titles): string
{
// `var` declares a variable. Its type comes from the value.
var $text = '';
foreach ($titles as string $title) {
$text = $text . '- ' . $title . "\n";
}
return $text . Core\Arr::count($titles) . " tasks\n";
}
}
array<string> $titles = ['Buy milk', 'Call Ada'];
// `[]` adds an item at the end of the array.
$titles[] = 'Water the plants';
echo Tasks::report($titles);
Output
- Buy milk
- Call Ada
- Water the plants
3 tasks

array<string> is an array whose values are strings. $titles[] = ... adds a value at the end.

foreach runs its body once for each value in the array. Core\Arr::count returns the number of values. Novis has many methods like it, and each one belongs to a class under Core.

Read more in Syntax: arrays and Syntax: foreach.

Next: step 3, classes and objects.