Creating arrays
Learn to create arrays with the array() and [] syntax.
What is an array?
An array is a way to store many values in a single variable. Instead of keeping three exam scores in separate variables, you can gather them in one array.
PHP creates arrays in two ways: with the array() function or with the [] short syntax. Modern PHP prefers []. For example, $scores = [85, 92, 78]; stores three scores in one array.
Indexed arrays
Each value in an array has an index. Values get indexes starting from 0 in the order they are added: the first element has index 0, the second 1, the third 2.
So in $scores = [85, 92, 78]; the index of 85 is 0, of 92 is 1 and of 78 is 2. Such arrays are called indexed arrays.
Exercise Print the first score
Define the $scores array with the values [85, 92, 78]. Then use echo to print the first score (index 0). Append "\n" at the end.
Show example solution
<?php
// Define the array and print the first score
$scores = [85, 92, 78];
echo $scores[0] . "\n";
Example solution:
<?php
// Define the array and print the first score
$scores = [85, 92, 78];
echo $scores[0] . "\n";
Test yourself
-
Which is a valid array definition?
- $scores = (85, 92, 78);
- $scores = [85, 92, 78];
- $scores = {85, 92, 78};
- $scores = 85, 92, 78;
Show answer
$scores = [85, 92, 78]; — Correct. The [] short syntax creates an array.
-
Complete the array definition
$scores = ____;Show answer
$scores = [85, 92, 78]; -
Match each array concept
- array()
- Function-form array
- []
- Short array syntax
- [0]
- Index of first element
- 85, 92, 78
- Comma-separated values
-
After $scores = [10, 20, 30]; how many elements are in the array?
$scores = [10, 20, 30];- 1
- 2
- 3
- 4
Show answer
3 — Correct. There are three comma-separated values: 10, 20 and 30.