Skip to content

Core\Str::padStart

Adds text before a string until it has the length you ask for.

Core\Str::padStart takes a string, a length and a padding. It adds copies of the padding before the string until the result has that many characters. The default padding is one space. When the padding has more than one character and does not fit a whole number of times, the last copy is cut short: padStart("5", 4, "ab") gives "aba5".

The length counts characters as a person sees them, so é or an emoji counts as one. If the string already has the length or more, it is returned unchanged. It is never cut.

An empty padding throws a RuntimeError when the string is too short.

Core\Str::padEnd adds the padding after the string instead.

Parameters

  • $sstringThe string to pad.
  • $lengthuintThe length to reach, in characters as a person counts them.
  • $paddingstringdefault " "The text to add. The last copy is cut short when only part of it fits. The default is one space.

Return value

Returns string. The padded string. If $s already has $length characters or more, it is returned unchanged.

Errors

  • RuntimeError$padding is empty and $s is shorter than $length. It is also thrown when the result is larger than this process can hold.

Examples

Numbers in a column

<?nvs
// Shows how to line up numbers on the right, so their last digits are in one column.
array<string> $amounts = ['7', '120', '4500'];
// `Core\Str::padStart` adds spaces before each number until it is 6 characters long.
// This prints ` 7`, ` 120` and ` 4500`.
foreach ($amounts as string $amount) {
echo Core\Str::padStart($amount, 6), "\n";
}
Output
7
120
4500

A longer padding

<?nvs
// Shows what happens when the padding has more than one character, and when
// the text is already long enough.
// The padding `-=` does not fit a whole number of times. The last copy is cut
// short, so this prints `-=-=-Café`. `é` counts as one character.
echo Core\Str::padStart('Café', 9, '-='), "\n";
// "Restaurant" already has 10 characters, so this prints it unchanged.
echo Core\Str::padStart('Restaurant', 6, '-='), "\n";
Output
-=-=-Café
Restaurant

Invoice numbers

<?nvs
// Shows how to give every invoice number the same width, with zeros in front.
array<uint> $orders = [7, 42, 1305];
// This prints `INV-00007`, `INV-00042` and `INV-01305`.
foreach ($orders as uint $order) {
echo 'INV-', Core\Str::padStart("{$order}", 5, '0'), "\n";
}
Output
INV-00007
INV-00042
INV-01305