array_pad
Pads an array with a value to a given length.
Syntax
array_pad(array $array, int $length, mixed $value): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The input array. |
| $length | int | The target length; negative pads on the left. |
| $value | mixed | The 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
- array_fill — Creates an array of identical values.
- str_pad — Pads a string to a given length.
- array_slice — Returns part of an array.
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.