Menu
Coddy logo textTech

Creating a 2D Array

Part of the Logic & Flow section of Coddy's PHP journey — lesson 27 of 68.

A multi-dimensional array is simply an array that contains other arrays as its elements. The most common type is a 2D array, which you can think of as a grid with rows and columns, similar to a spreadsheet or a game board.

Creating a 2D array in PHP is straightforward—you build an array where each element is itself an array:

<?php
$gameBoard = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
];
?>

This creates a 3x3 grid where each inner array represents a row, and each element within those arrays represents a column. You can also create 2D arrays with different data types:

<?php
$scores = [
    [85, 92, 78],
    [90, 88, 95],
    [76, 84, 89]
];
?>

PHP also provides a built-in function called array_fill() that lets you quickly create an array filled with a specific value. It takes three arguments: the starting index, the number of elements, and the value to fill:

<?php
// array_fill(start_index, num_elements, value)
$row = array_fill(0, 3, 0); // [0, 0, 0]
?>

You can combine array_fill() with itself to build a 2D array efficiently. For example, to create a 3x3 grid where every cell starts at 0:

<?php
$grid = array_fill(0, 3, array_fill(0, 3, 0));
// Result: a 3x3 array where every element is 0
?>

Multi-dimensional arrays are incredibly useful for organizing structured data like game boards, tables of information, or any scenario where you need to represent data in a grid format. They provide a natural way to work with rows and columns of related information.

challenge icon

Challenge

Easy

You will receive three inputs representing the dimensions and initial value for a 2D array: the number of rows, the number of columns, and a value to fill each position. Read these inputs, create a 2D array with the specified dimensions where each element is set to the given value, and print the array using print_r().

Input format:

  • First line: Number of rows (integer)
  • Second line: Number of columns (integer)
  • Third line: Initial value for each element (string)

Expected output: The created 2D array displayed using print_r()

Try it yourself

<?php
// Read input
$rows = intval(fgets(STDIN));
$columns = intval(fgets(STDIN));
$value = trim(fgets(STDIN));

// TODO: Write your code below to create the 2D array


// Output the result
print_r($array);
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow