Version: v0.6.1 - Beta.  We welcome contributors & feedback.  THanks!

Lists

A List is a variable that can hold multiple values.

Each item, or element, is separated by a comma.

// A list of strings
$letters = ['a', 'b', 'c'];

// A list of numbers
$evenNumbers = [2, 4, 6, 8, 10];

// Multi-line format
$countries = [
    'Argentina',
    'Brazil',
    'Chile'
];

// Each item can be an expression
$nums = [1 + 9, 2 + 8];

JargonIn other languages, Lists are often called Arrays.

List Elements

You can access elements of a list by the index number of its position.

THT lists use zero-based indexes: the first element is 0, the second element is 1, etc.

$letters = ['a', 'b', 'c', 'd'];

$first = $letters[0];  //= 'a'
$second = $letters[1]; //= 'b'

// Negative indexes start counting from the end
$last = $letters[-1];        //= 'd'
$nextToLast = $letters[-2];  //= 'c'

// Modify an index directly
$letters[0] = 'x';
print($letters);
//= ['x', 'b', 'c', 'd']

List Methods

Here are some common List methods.

$colors = ['red', 'blue'];

$colors.contains('blue');
//= true

$colors.length();
//= 2

$colors.join(' & ');
//= 'red & blue'

The methods push and pop treat the List as a stack of items. They add and remove the last item in the List.

(Tip: Think of a spring-loaded stack of plates in a cafeteria.)

$colors = ['red', 'blue'];

// Add an item to the end
$colors.push('yellow');
//= ['red', 'blue', 'yellow']

// Remove item from the end and return it
$colors.pop();  //= 'yellow'

print($colors);
//= ['red', 'blue']

The methods insert and remove let you add and delete items anywhere in the List.

$colors = ['red', 'blue'];

// Add item to the 2nd slot (index: 1)
$colors.insert('orange', 1);
//= ['red', 'orange', 'blue']

// Remove item from beginning (index: 0)
$colors.remove(0);  //= 'red'

print($colors);
//= ['orange', 'blue']

See Also