CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

index.php
<?php
// Define the array and print the first score

Sample solution

index.php
<?php
// Define the array and print the first score
$scores = [85, 92, 78];
echo $scores[0] . "\n";

Expected output

85

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid array definition?

  • $scores = (85, 92, 78);
  • $scores = [85, 92, 78]; Correct answer
  • $scores = {85, 92, 78};
  • $scores = 85, 92, 78;

Explanation: The [] short syntax creates an array.

2 Complete the array definition

Question
$scores = ____;
Answer
$scores = [85, 92, 78];

Explanation: Values separated by commas inside square brackets form an array.

3 Match each array concept

Term Meaning
array() Function-form array
[] Short array syntax
[0] Index of first element
85, 92, 78 Comma-separated values

4 After $scores = [10, 20, 30]; how many elements are in the array?

index.php
$scores = [10, 20, 30];
  • 1
  • 2
  • 3 Correct answer
  • 4

Explanation: There are three comma-separated values: 10, 20 and 30.

All lessons in Beginner