Lists
A List is a variable that can hold zero or more values in a sequential order.
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 (no commas) $countries = [ 'Turkey' 'Tanzania' 'Tonga' ] // 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.
Unlike PHP, indexes start at 1 and count up.
For example:
$colors = ['red', 'green', 'blue', 'orange'] index value ----- ----- 1 red 2 green 3 blue 4 orange
You can access elements by putting the index in brackets, e.g. $myList[3]
.
$colors = ['red', 'orange', 'green', 'blue'] $colors[1] //= 'red' $colors[2] //= 'orange' // Negative indexes start counting from the end $colors[-1] //= 'blue' $colors[-2] //= 'green' // You can modify an index directly $colors[1] = 'yellow' print($colors) //= ['yellow', 'orange', 'green', 'blue']
List Methods
Here are some common List methods.
$colors = ['red', 'blue', 'green'] $colors.contains('blue') //= true $colors.length() //= 3 $colors.sort() ['blue', 'green', 'red'] $colors.join(', ') //= 'red, blue, green'
See the List class for all other methods.
Adding/Removing Items
The methods push
and pop
will add and remove items at end of the List, treating it as a stack.
Fun FactThe names “push” and “pop” come from the analogy 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 $colors.insert('orange', 2) //= ['red', 'orange', 'blue'] // Remove item from beginning $colors.remove(1) //= 'red' print($colors) //= ['orange', 'blue']
Push Operator #=
Because pushing items onto lists is a very common task, THT provides a shortcut.
$list = ['red', 'blue'] $list #= 'yellow' print($list) //= ['red', 'blue', 'yellow']