Lesson 8 of 100
Arrays10 min5 checksPHP 8.5

Create an indexed array and append to it

Learn how to create an indexed PHP array, read items by position, and append new values with [] without disturbing the entries already there.

01 · THE IDEAREAD → TRY → LEARN

What an array is

A PHP array is an ordered map: it links keys to values. For a simple list you do not have to choose the keys. PHP numbers the items for you, starting at 0.

You can create an array with the short syntax []. Read an item by putting its key in square brackets after the variable.

Example
<?php
$colors = ["red", "green", "blue"];
echo $colors[0], " ", $colors[2], " ", count($colors);
Output
red blue 3

The first item has key 0, so the last of three items has key 2. The function count() returns how many items the array holds. Asking for a key that does not exist produces a warning and gives null, so check the position you request.

Appending with empty brackets

To add to the end of an array, assign to $array[]. When you leave the key out, PHP uses the largest integer key used so far plus one. Existing entries stay where they are.

If you assign an explicit key, later appends continue from the highest integer key:

Example
<?php
$numbers = [10, 20];
$numbers[] = 30;
$numbers[7] = 70;
$numbers[] = 80;
echo implode(",", array_keys($numbers)), "|", implode(",", $numbers);
Output
0,1,2,7,8|10,20,30,70,80

The keys are 0, 1, 2, 7, 8. Appending never overwrites an earlier item, but it can leave gaps if you have set keys by hand.

Arrays passed to functions

When you pass an array to a function, the function receives its own copy by default. If you append inside the function and return the array, the caller's original variable is unchanged unless it assigns the result back. This makes small helper functions easy to reason about: they take a list and return a new list.

Common mistakes

  • Writing $items[0] = $item replaces the first entry instead of adding one.
  • Returning [$item] creates a brand-new array and throws away everything that was passed in.
  • Using array_unshift() adds the value to the front, not the end.

Practice

Write append_item so it returns the original list with the new item placed last.

Before you start

Variables · Strings

You’ll practice
  • Create an indexed array
  • Append a value without losing existing entries
Your task

Make append_item() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.