Skip to content

Core\Arr::fill

Core\Arr::fill(uint $count, T $value): array<T>Core\Arr::fill(
    uint $count,
    T $value,
): array<T>

Returns a list of the same value repeated, under the keys 0, 1, 2 and so on.

You give the number of entries and the value each one holds. A count of 0 returns an empty array. The keys always start at 0, so there is no start index. When you want your own keys, use Core\Arr::fillKeys with the list of keys.

A count so large that the array does not fit in memory throws an error. That matters when the count comes from a request, because nothing else limits it.

The examples below show a list of counters, the placeholders of a database query, and a grid built from two fills.

Parameters

  • $countuintHow many entries; 0 yields the empty array.
  • $valueTThe value of every entry.

Return value

Returns array<T>. A list of $count entries.

Errors

  • RuntimeErrorThe result for $count is larger than the largest array this process can store.

Examples

The same value repeated

<?nvs
// Shows how to build a list that holds the same value several times.
// Four entries, each of them 0. The keys are 0, 1, 2 and 3.
array<int> $counters = Core\Arr::fill(4, 0);
// This prints 4 and then 0.
echo Core\Arr::count($counters), "\n";
echo $counters[0], "\n";
Output
4
0

Placeholders for a query

<?nvs
// Shows how to build the placeholders of a database query. A query needs one
// `?` for every value you send with it.
array<string> $ids = ['7', '9', '12'];
// One question mark per id, joined into one text.
string $marks = Core\Str::join(Core\Arr::fill(Core\Arr::count($ids), '?'), ', ');
// This prints SELECT name FROM users WHERE id IN (?, ?, ?).
echo 'SELECT name FROM users WHERE id IN (', $marks, ')', "\n";
Output
SELECT name FROM users WHERE id IN (?, ?, ?)

A grid of cells

<?nvs
// Shows how to build a grid. A game or a report does this before it writes the
// cells.
// Three rows, each one a list of three zeros.
array<array<int>> $grid = Core\Arr::fill(3, Core\Arr::fill(3, 0));
// Every row is a copy of its own, so this writes one cell in one row.
$grid[1][2] = 5;
// This prints three rows of three numbers. Only the middle row has the 5.
foreach ($grid as array<int> $row) {
foreach ($row as int $cell) {
echo $cell, ' ';
}
echo "\n";
}
Output
0 0 0
0 0 5
0 0 0