PHP Reference ยท Array Functions
PHP array_pad() function
Reference for PHP array_pad(): extend an array to a minimum length by adding a value at the end or the start, and how keys are treated.
array_pad() makes sure an array has at least a given number of elements by adding copies of a value. A positive length pads at the end; a negative length pads at the beginning.
If the array is already long enough, it is returned unchanged. The function never truncates. It is handy for fixed-width rows, such as making every line of a table the same length.
<?php print_r(array_pad([1, 2], 4, 0)); // [1, 2, 0, 0] print_r(array_pad([1, 2], -4, 0)); // [0, 0, 1, 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_pad(array $array, int $length, mixed $value): array
| Name | Description |
|---|---|
$array |
The input array. |
$length |
The minimum length of the result. Positive pads at the end, negative pads at the start (the absolute value is the target length). |
$value |
The value used for the new elements. |
Return value: the padded array, or the original contents if no padding is needed.
Errors: a ValueError is thrown if the resulting array would be unreasonably large.
Usage notes
- Keys: string keys are preserved; integer keys are renumbered, as in
array_merge(). - No truncation. To cut an array down to a maximum length use
array_slice(). - Defaults for
explode():array_pad(explode(...), $n, $default)guarantees enough pieces for list destructuring and avoids "undefined array key" warnings. - The same value goes into every new slot; objects are shared between slots (see
array_fill()). - Strings are padded with
str_pad(), not with this function.
Related
array_fill(),array_slice(),str_pad(),array_merge()- Lessons: Arrays, Array functions