Modifying 2D Array Elements
Part of the Logic & Flow section of Coddy's PHP journey — lesson 29 of 68.
Once you can access elements in a 2D array, the next logical step is learning how to change their values. Modifying elements in a 2D array uses the same double-indexing syntax as accessing them, but with an assignment operator to set a new value.
Here's how you modify a specific element in a 2D array:
<?php
$gameBoard = [
["", "", ""],
["", "", ""],
["", "", ""]
];
// Change the center cell to 'X'
$gameBoard[1][1] = "X";
// Change the top-left corner to 'O'
$gameBoard[0][0] = "O";
?>The syntax $gameBoard[1][1] = "X" targets row 1, column 1 (the center of a 3x3 grid) and assigns the value "X" to that position. This directly modifies the original array, replacing whatever value was there before.
This modification technique is essential for updating game states, changing data in tables, or any scenario where you need to alter specific positions within your grid-like data structure. The ability to pinpoint and update exact locations makes 2D arrays perfect for representing dynamic, changeable information organized in rows and columns.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive four inputs: a 2D array representing a seating chart in JSON format, a row index, a column index, and a new passenger name. Read all four inputs, convert the JSON string to a 2D array, modify the element at the specified row and column by assigning the new passenger name, and print the updated 2D array using print_r().
The 2D array represents a seating chart where each element contains a passenger name or an empty string for vacant seats.
Input format:
- First line: A JSON array representing the seating chart (example:
[["Alice","Bob",""],["","Charlie","Diana"],["","",""]]) - Second line: Row index (integer)
- Third line: Column index (integer)
- Fourth line: New passenger name (string)
Expected output: The modified 2D array displayed using print_r()
Cheat sheet
To modify elements in a 2D array, use double-indexing syntax with an assignment operator:
$array[row][column] = newValue;Example modifying a game board:
<?php
$gameBoard = [
["", "", ""],
["", "", ""],
["", "", ""]
];
// Change the center cell to 'X'
$gameBoard[1][1] = "X";
// Change the top-left corner to 'O'
$gameBoard[0][0] = "O";
?>This directly modifies the original array, replacing the value at the specified position. The modification technique is essential for updating dynamic data organized in rows and columns.
Try it yourself
<?php
// Read inputs
$json_input = trim(fgets(STDIN));
$row_index = intval(fgets(STDIN));
$col_index = intval(fgets(STDIN));
$new_passenger = trim(fgets(STDIN));
// Convert JSON to 2D array
$seating_chart = (array)json_decode($json_input, true);
// TODO: Write your code below to modify the seating chart
// Output the modified array
print_r($seating_chart);
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting