Skip to content

Core\Arr::padEnd

Core\Arr::padEnd(array<T> $a, uint $size, T $value): array<T>Core\Arr::padEnd(
    array<T> $a,
    uint $size,
    T $value,
): array<T>

Returns a new array with copies of a value added at the end, until the array has the length you asked for.

Core\Arr::padEnd never changes the array you give it. The result is always a list: its keys are numbers counting from "0", and the keys your array had are gone. Every value of your array comes first, then the copies.

An array that is already that long, or longer, is not padded. You get its values back as a list.

Good to know: the number you pass is the length of the whole result. It is not the number of copies to add.

Parameters

  • $aarray<T>The array to pad.
  • $sizeuintThe length to reach; an array already that long is not padded.
  • $valueTThe value of every added entry.

Return value

Returns array<T>. A list renumbered from "0". Every key is discarded, padded or not.

Errors

  • RuntimeErrorThe padded result is larger than the largest array this process can store.

Examples

Always five entries

<?nvs
// Shows how to add values at the end of an array until it has the length you
// want.
array<string> $picked = ['red', 'blue'];
// `Core\Arr::padEnd` adds copies of "free" at the end until there are five
// entries. This prints "red blue free free free".
array<string> $slots = Core\Arr::padEnd($picked, 5, 'free');
echo Core\Str::join($slots, ' '), "\n";
// Your own array is not changed, so this prints 2.
echo Core\Arr::count($picked), "\n";
Output
red blue free free free
2

An array with text keys

<?nvs
// Shows the result for an array whose keys are words, and what happens when
// the array is already long enough.
array<string> $named = ['a' => 'one', 'b' => 'two'];
// The keys of the result are numbers, so the words are gone.
// This prints "0 1 2".
array<string> $padded = Core\Arr::padEnd($named, 3, '');
echo Core\Str::join(Core\Arr::keys($padded), ' '), "\n";
// The array already has two entries, so nothing is added. You get its values
// back as a list. This prints "one two".
array<string> $same = Core\Arr::padEnd($named, 2, '');
echo Core\Str::join($same, ' '), "\n";
Output
0 1 2
one two

Every row as wide as the header

<?nvs
// Shows how to make a row of a table as wide as its header before you write
// the row out. A row that is missing values gets empty text at the end.
array<string> $header = ['name', 'city', 'phone', 'email'];
array<string> $row = ['Ada', 'London'];
array<string> $full = Core\Arr::padEnd($row, Core\Arr::count($header), '');
// The two missing fields are empty, so this prints "Ada;London;;".
echo Core\Str::join($full, ';'), "\n";
// The row is now as wide as the header, so this prints 4.
echo Core\Arr::count($full), "\n";
Output
Ada;London;;
4