CodeBlanks Logo Icon CodeBlanks

Accessing array elements

PHP course · Beginner · Lesson 54/116

Learn to access array elements by index with square brackets.

Access with square brackets

To access an element of an array, write its index inside square brackets after the variable name: $scores[0], $scores[1], $scores[2] and so on.

For example, in $scores = [85, 92, 78]; the value of $scores[0] is 85, $scores[1] is 92 and $scores[2] is 78. You can print these values with echo.

Missing index and isset()

If an element at an index does not exist, PHP gives a warning and the result is null. For example, in a three-element $scores array, $scores[5] is missing.

You can check whether an index is filled with isset(): isset($scores[2]) returns true, isset($scores[5]) returns false. This lets you guard before safely accessing an element that may not exist.

Exercise Print the first and last score

Use the definition $scores = [85, 92, 78];. First echo the first score (index 0), then the last score (index 2). Append "\n" to each. Expected output: 85, then 78, on separate lines.

Show example solution
<?php
$scores = [85, 92, 78];
// Print the first and last score
echo $scores[0] . "\n";
echo $scores[2] . "\n";
Example solution:
<?php
$scores = [85, 92, 78];
// Print the first and last score
echo $scores[0] . "\n";
echo $scores[2] . "\n";

Test yourself

  1. If $scores = [85, 92, 78]; what does $scores[1] return?

    $scores = [85, 92, 78];
    echo $scores[1];
    • 92
    • 78
    • 85
    • 1
    Show answer

    92 — Correct. Index 1 gives the second element, 92.

  2. Access the second element

    $scores = [85, 92, 78];
    echo $scores____;
    
    Show answer
    $scores = [85, 92, 78];
    echo $scores[1];
    
  3. Match each index to its value

    $scores[0]
    85
    $scores[1]
    92
    $scores[2]
    78
  4. What is the index of the last element in a three-element array?

    $scores = [85, 92, 78];
    • 3
    • 1
    • 0
    • 2
    Show answer

    2 — Correct. For three elements the indexes are 0, 1 and 2; the last is 2.

All lessons in Beginner