Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_pad

Pads an array with a value to a given length.

Syntax

array_pad(array $array, int $length, mixed $value): array

Parameters

ParameterTypeDescription
$arrayarrayThe input array.
$lengthintThe target length; negative pads on the left.
$valuemixedThe value to pad with.

Return value

arrayA new array.

Examples

Padding on the right and on the left:

<?php
 
echo json_encode(array_pad([1, 2], 5, 0)), "\n";
echo json_encode(array_pad([1, 2], -5, 0));

Output:

[1,2,0,0,0]
[0,0,0,1,2]

Notes

If the array is already at least that long, it is returned unchanged.

See also

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.