In PHP, array_fill() is a very convenient function to fill an array with specified values. It is usually used to initialize arrays, especially when we need to quickly generate an array of default values. However, many developers are prone to fall into common misunderstandings when using array_fill() to create two-dimensional arrays, which leads to unexpected behavior in the program. This article will explore these common mistakes and how to avoid them correctly.
Before digging into the question, let’s briefly review the basic usage of array_fill() :
$filledArray = array_fill(0, 5, 'default');
// result: ['default', 'default', 'default', 'default', 'default']
This function accepts three parameters:
Start index (from which index to start filling)
Array length (filled with several elements)
Fill value
When we try to use array_fill() to create a two-dimensional array, such as 5 lines, each with 3 default values 'default' , many developers will write the following code:
$matrix = array_fill(0, 5, array_fill(0, 3, 'default'));
At first glance, this way of writing seems reasonable. The output result is also as expected:
[
['default', 'default', 'default'],
['default', 'default', 'default'],
['default', 'default', 'default'],
['default', 'default', 'default'],
['default', 'default', 'default']
]
But the problem is: these subarrays are actually references to the same array !
That is, if we modify the value of one of the subarrays:
$matrix[0][0] = 'changed';
This causes the first value of all rows to become 'changed' :
[
['changed', 'default', 'default'],
['changed', 'default', 'default'],
['changed', 'default', 'default'],
['changed', 'default', 'default'],
['changed', 'default', 'default']
]
This is because array_fill() is filled with references to the same array when the third parameter is an array, rather than creating a new array instance at a time.
To solve this problem, we need to make sure that each subarray is an independent instance. The safest way is to use loops:
$matrix = [];
for ($i = 0; $i < 5; $i++) {
$matrix[$i] = array_fill(0, 3, 'default');
}
This ensures that the array of each row is a new copy and will not affect each other.
If you encapsulate a function that creates a two-dimensional array, be careful not to create subarrays outside the function and then reuse them. For example:
Error demonstration:
function createMatrix($rows, $cols, $defaultValue) {
$rowTemplate = array_fill(0, $cols, $defaultValue);
return array_fill(0, $rows, $rowTemplate);
}
This problem is the same as described above, all lines refer to the same $rowTemplate . Modifying one line will affect all lines.
Correct writing:
function createMatrix($rows, $cols, $defaultValue) {
$matrix = [];
for ($i = 0; $i < $rows; $i++) {
$matrix[] = array_fill(0, $cols, $defaultValue);
}
return $matrix;
}
Suppose you are building an online fill-in-the-blank question generation tool (such as https://m66.net/tools/quiz-generator ), you need to create a blank question board, where the default value for each box is null :
$questionBoard = [];
for ($i = 0; $i < 10; $i++) {
$questionBoard[] = array_fill(0, 5, null);
}
This approach can avoid accidentally sharing memory on the entire question board, causing bugs in user interaction or subsequent logic.
array_fill() is an efficient tool, but when it comes to nested arrays (two-dimensional or multi-dimensional), we must be wary of shared references . By using loops and ensuring that each subarray is a new instance, we can build more robust and predictable data structures.
Understanding the value and reference mechanism in PHP not only helps avoid this problem, but also improves your ability to deal with complex array structures in large projects.