Current Location: Home> Latest Articles> How to create a multidimensional array in combination with for loops and array_fill()

How to create a multidimensional array in combination with for loops and array_fill()

M66 2025-06-05

In PHP, creating multidimensional arrays can be implemented in many ways. One common method is to use a for loop to combine the array_fill() function to generate. The array_fill() function can be used to fill the specified position of an array, and can be combined with a for loop to create a multidimensional array with the same element value. This article will use an example to show how to use this method.

What is the array_fill() function?

The basic function of the array_fill() function is to fill the array with the specified value, and the starting index and length of the fill are user-defined. The basic syntax is as follows:

 array_fill(int $start_index, int $num, mixed $value): array
  • $start_index : The start index of the fill.

  • $num : The number of elements to be filled.

  • $value : The value of the padding.

How to create a multidimensional array in combination with for loop with array_fill()?

We can call array_fill() multiple times through a for loop to generate a multidimensional array. Here is a simple example showing how to use a for loop in conjunction with array_fill() to generate a 3x3 2D array with the value of "example" for each position:

 <?php

// Define the number of rows and columns of a multidimensional array
$rows = 3;
$cols = 3;

// Create an empty array to store multidimensional arrays
$multiDimensionalArray = array();

// use for Looping 2D array
for ($i = 0; $i < $rows; $i++) {
    // 每一行都use array_fill filling
    $multiDimensionalArray[$i] = array_fill(0, $cols, 'example');
}

// Printout array
print_r($multiDimensionalArray);

?>

Code parsing:

  1. Initialize array : First, an empty array $multiDimensionalArray is defined to store our multidimensional array.

  2. Looping array : Through a for loop, we generate multiple rows of data. Each line is filled by the array_fill() function. array_fill(0, $cols, 'example') means to fill from index 0 , and fill $cols 'example' strings.

  3. Output result : Use print_r() to print the result of a multidimensional array.

Output result:

 Array
(
    [0] => Array
        (
            [0] => example
            [1] => example
            [2] => example
        )

    [1] => Array
        (
            [0] => example
            [1] => example
            [2] => example
        )

    [2] => Array
        (
            [0] => example
            [1] => example
            [2] => example
        )
)

Extension: Create deeper multidimensional arrays using array_fill()

If you need to create a deeper multi-dimensional array, such as a 3x3x3 3 array, you can use array_fill() again on each row. Here is an example to create a 3x3x3 3 3D array with each element "m66.net" :