Modifying Elements by Index
Part of the Fundamentals section of Coddy's PHP journey — lesson 37 of 71.
You've learned how to access array elements by their index. Now let's see how to change those elements. Modifying an array element uses the same square bracket syntax, but with an assignment.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry";
echo $fruits[1]; // Blueberry
?>Here, we replaced "Banana" at index 1 with "Blueberry". The original value is gone—arrays don't keep a history of changes.
You can modify any element as long as you know its index:
<?php
$scores = [85, 90, 78];
$scores[0] = 95; // Update first score
$scores[2] = 82; // Update last score
echo $scores[0]; // 95
echo $scores[2]; // 82
?>This is useful when you need to update data in your list—like correcting a typo, updating a price, or changing a user's status. The index tells PHP exactly which element to replace, leaving all other elements untouched.
Challenge
EasyRead a line of input containing comma-separated values representing a list of colors (e.g., Red,Green,Blue,Yellow).
Then read three more inputs:
- An integer
index1representing the first index to modify - A string
newValue1representing the new value for that index - An integer
index2representing the second index to modify
Create an array from the comma-separated input, then:
- Modify the element at
index1to benewValue1 - Modify the element at
index2to bePurple
Print the modified array elements on separate lines, in order from index 0 to the last index.
Example:
If the inputs are Red,Green,Blue,Yellow, 0, Orange, and 2, the output should be:
Orange
Green
Purple
YellowIf the inputs are Apple,Banana,Cherry,Mango,Kiwi, 1, Grape, and 4, the output should be:
Apple
Grape
Cherry
Mango
PurpleCheat sheet
To modify an array element, use the index with square brackets and assignment:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Changes "Banana" to "Blueberry"
echo $fruits[1]; // Blueberry
?>You can modify multiple elements by specifying different indices:
<?php
$scores = [85, 90, 78];
$scores[0] = 95; // Update first element
$scores[2] = 82; // Update last element
?>The original value is replaced and not preserved. Other elements in the array remain unchanged.
Try it yourself
<?php
// Read the comma-separated colors
$colorsInput = trim(fgets(STDIN));
$colors = explode(',', $colorsInput);
// Read the modification inputs
$index1 = intval(trim(fgets(STDIN)));
$newValue1 = trim(fgets(STDIN));
$index2 = intval(trim(fgets(STDIN)));
// TODO: Write your code here
// 1. Modify the element at index1 to be newValue1
// 2. Modify the element at index2 to be "Purple"
// Output each element on a separate line
foreach ($colors as $color) {
echo $color . "\n";
}
?>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