array_pad
array_pad(array $array, int $length, mixed $value): array
Pads an array to a given length: positive pads right, negative pads left, and the array is returned untouched when long enough; pairs with array_slice as the truncate+pad pagination combo.
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
/* right pad to 5 with '.': the array keeps room for the '\0' */
char right[6] = { 0 };
right[0] = 'a'; right[1] = 'b';
memset(right + 2, '.', 3);
printf("%s\n", right);
/* left pad: fill first, then place the data at the end */
char left[6] = { 0 };
memset(left, '#', 3);
left[3] = 'a'; left[4] = 'b';
printf("%s\n", left);
return 0;
}
ab... ###ab
C++ C++26
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> short_vec = { "a", "b" };
// right pad: resize appends the fill value
std::vector<std::string> right = short_vec;
right.resize(5, ".");
for (const auto& s : right) std::cout << s;
std::cout << "\n";
// left pad: insert the fill at the front
std::vector<std::string> left = short_vec;
left.insert(left.begin(), 3, "#");
for (const auto& s : left) std::cout << s;
std::cout << "\n";
return 0;
}
ab... ###ab
C# v11.0.100
using System.Collections.Generic;
using System.Linq;
class MainClass {
static void Main() {
var shortList = new List<string> { "a", "b" };
var right = shortList.Concat(Enumerable.Repeat(".", 3)).ToList();
System.Console.WriteLine(string.Join("", right)); // ab...
var left = Enumerable.Repeat("#", 3).Concat(shortList).ToList();
System.Console.WriteLine(string.Join("", left)); // ###ab
}
}
ab... ###ab
Go v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
short := []string{"a", "b"}
// right pad: copy first to avoid aliasing the backing array
right := append(append([]string{}, short...), ".", ".", ".")
fmt.Println(strings.Join(right, ""))
// left pad
left := append([]string{"#", "#", "#"}, short...)
fmt.Println(strings.Join(left, ""))
}
ab... ###ab
Java v27.0.1
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> shortList = new ArrayList<>(List.of("a", "b"));
// nCopies builds an immutable filler list; append after the data
List<String> right = new ArrayList<>(shortList);
right.addAll(Collections.nCopies(3, "."));
System.out.println(String.join("", right));
// left pad: the filler comes first
List<String> left = new ArrayList<>(Collections.nCopies(3, "#"));
left.addAll(shortList);
System.out.println(String.join("", left));
}
}
ab... ###ab
JavaScript v26.13.1
const shortList = ["a", "b"];
const right = [...shortList, ...Array(3).fill(".")];
console.log(right.join("")); // ab...
const left = [...Array(3).fill("#"), ...shortList];
console.log(left.join("")); // ###ab
ab... ###ab
PHP v8.6.0
$short = ["a", "b"];
echo json_encode(array_pad($short, 5, ".")), "\n"; // right pad
echo json_encode(array_pad($short, -5, "#")), "\n"; // negative: LEFT pad
echo json_encode(array_pad($short, 2, "x")), "\n"; // already long enough: untouched
echo json_encode(array_pad($short, 1, "x")), "\n"; // never truncates
["a","b",".",".","."] ["#","#","#","a","b"] ["a","b"] ["a","b"]
Python v3.15.2
short_list = ["a", "b"]
# PHP's negative-length (left pad) semantics are unique to PHP -
# in Python you spell the direction out explicitly
right = short_list + ["."] * 3
print("".join(right)) # ab...
left = ["#"] * 3 + short_list
print("".join(left)) # ###ab
ab... ###ab
Rust v1.99.1
fn main() {
let short_list = vec!["a", "b"];
// right pad: chain the fill after the data, take n total
let right: Vec<_> = short_list
.iter()
.copied()
.chain(std::iter::repeat("."))
.take(5)
.collect();
println!("{}", right.concat());
// left pad: repeat first, then the data
let left: Vec<_> = std::iter::repeat("#")
.take(3)
.chain(short_list.iter().copied())
.collect();
println!("{}", left.concat());
}
ab... ###ab
TypeScript v26.13.1
const shortList: string[] = ["a", "b"];
const right: string[] = [...shortList, ...Array(3).fill(".")];
console.log(right.join("")); // ab...
const left: string[] = [...Array(3).fill("#"), ...shortList];
console.log(left.join("")); // ###ab
ab... ###ab
Language differences
C: fixed-size arrays + memset (example); the key trap is the \0 slot - char right[5] with 3 chars filled at [2..4] swallows the terminator, so the array must be sized 6; left padding is fill-then-place.
C++: resize(5, ".") pads right only; left needs insert(begin(), 3, "#") (example); the directional asymmetry is typical of the STL.
C#: Concat(Enumerable.Repeat(...)) composition (example); string.PadLeft/PadRight is the string-side counterpart; LINQ is lazy - ToList materializes.
Go: append(append([]string{}, short...), ...) (example) - copy first to avoid aliasing (append can mutate the original slice's backing array); left pad is simply append(fill, short...).
Java: Collections.nCopies(3, ".") (example) builds an immutable filler list before addAll; String.join prints; Java has no native spread, composition is the idiom.
JavaScript: Array(3).fill(".") + spread (example); beware new Array(3).map(...) - sparse-array trap (map skips holes), fill first; string-side padStart/padEnd (ES2017) is the counterpart.
PHP: NEGATIVE length = left pad is the most distinctive semantic (example); when length <= size the array is NEVER truncated and returned untouched - pad only, never cut; pairs with array_slice: slice truncates, pad completes - pagination assembly; padding more than 1048576 elements at once raises E_WARNING.
Python: + and * composition (example); explicit direction is the Python philosophy; itertools.repeat + islice is the lazy variant; str.ljust/rjust on the string side.
Rust: chain(repeat).take(n) (example) - repeat is infinite, take caps it: elegant and allocation-free in between; note .copied() to dereference.
TypeScript: same as JS (example); Array(3).fill(".") infers any[] - annotate the element type to keep as any from spreading.