Adding Elements to an Array
Part of the Fundamentals section of Coddy's PHP journey — lesson 39 of 71.
You've learned how to modify existing elements, but what about adding new elements to an array? PHP makes this simple with the empty bracket syntax.
To add an element to the end of an array, use empty square brackets on the left side of an assignment:
<?php
$fruits = ["Apple", "Banana"];
$fruits[] = "Cherry";
$fruits[] = "Date";
echo count($fruits); // 4
?>Each time you use $array[] = value, PHP automatically assigns the next available index. In the example above, "Cherry" gets index 2 and "Date" gets index 3.
This is particularly useful when you start with an empty array and build it up over time:
<?php
$shoppingList = [];
$shoppingList[] = "Milk";
$shoppingList[] = "Bread";
$shoppingList[] = "Eggs";
echo $shoppingList[0]; // Milk
echo $shoppingList[2]; // Eggs
?>The empty bracket syntax always appends to the end of the array, so you don't need to calculate or track the next index yourself. PHP handles it automatically.
Challenge
EasyRead a line of input containing comma-separated values representing initial items in a list (e.g., Apple,Banana).
Then read three more inputs:
- A string
item1to add to the array - A string
item2to add to the array - A string
item3to add to the array
Create an array from the comma-separated input, then add the three new items to the end of the array using the empty bracket syntax.
Print the following on separate lines:
- The total count of items in the array after adding all three
- The element at index
2 - The last element of the array (use
count()to find the last index)
Example:
If the inputs are Apple,Banana, Cherry, Date, and Elderberry, the output should be:
5
Cherry
ElderberryIf the inputs are Red,Blue,Green, Yellow, Purple, and Orange, the output should be:
6
Green
OrangeCheat sheet
To add elements to the end of an array, use empty square brackets [] on the left side of an assignment:
<?php
$fruits = ["Apple", "Banana"];
$fruits[] = "Cherry";
$fruits[] = "Date";
echo count($fruits); // 4
?>PHP automatically assigns the next available index each time you use $array[] = value.
This works with empty arrays too:
<?php
$shoppingList = [];
$shoppingList[] = "Milk";
$shoppingList[] = "Bread";
$shoppingList[] = "Eggs";
echo $shoppingList[0]; // Milk
echo $shoppingList[2]; // Eggs
?>To access the last element of an array, use count($array) - 1 as the index:
<?php
$items = ["A", "B", "C"];
echo $items[count($items) - 1]; // C
?>Try it yourself
<?php
// Read the comma-separated initial items
$input = trim(fgets(STDIN));
$items = explode(',', $input);
// Read the three items to add
$item1 = trim(fgets(STDIN));
$item2 = trim(fgets(STDIN));
$item3 = trim(fgets(STDIN));
// TODO: Write your code below
// Add the three items to the array using empty bracket syntax
// Then print:
// 1. The total count of items
// 2. The element at index 2
// 3. The last element (use count() to find the last index)
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators6Arrays Part 1 - Indexed
Introduction to ArraysCreating Indexed ArraysAccessing Elements by IndexModifying Elements by IndexArray Size with CountAdding Elements to an ArrayRecap - Managing a Simple List