Skip to Content
Learn
Ordered Arrays
Adding and Changing Elements

We can make adjustments to existing arrays—we don’t have to create a new array when we want our array to change.

We add elements to the end of an array by taking the variable name and appending square brackets ([]), the assignment operator (=), and the element we want to add:

$string_array = ["first element", "second element"]; $string_array[] = "third element"; echo implode(", ", $string_array); // Prints: first element, second element, third element

We can also reassign the individual elements in an array:

$string_array = ["first element", "second element", "third element"]; $string_array[0] = "NEW! different first element"; echo $string_array[0]; // Prints: NEW! different first element"

In the code above, we replaced the original string held in the array ("first element") with a new string value: "NEW! different first element".

Instructions

1.

We’re going to have you make several changes to the provided $change_me array without making any changes to how it’s initially declared (line 4).

First, add a string element to the end of the array.

2.

Great! Add another element to the end of the array. This time it should be an integer.

3.

Reassign the 1st index location of the array (which currently holds the value 6) to hold the value "tadpole".

4.

Awesome! Let’s take a look at this array of yours. Print your array to the terminal.

Folder Icon

Take this course for free

Already have an account?