The array_pad Function
The array_pad
function pads an array
to a specified size with a value.
The first parameter is the array to pad,
the second parameter is the target size,
and the third is the padding value.
The second parameter can be negative - in this case, the array will be padded from the beginning, not from the end.
Syntax
array_pad(array $array, int $length, mixed $value): array
Example
Let's pad the array with zeros so that
its size becomes 7
elements:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_pad($arr, 7, 0);
var_dump($res);
?>
Code execution result:
['a', 'b', 'c', 'd', 'e', 0, 0]
Example
Now the array already has 7
elements
- so it won't be padded with anything:
<?php
$arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
$res = array_pad($arr, 7, 0);
var_dump($res);
?>
Code execution result:
['a', 'b', 'c', 'd', 'e', 'f', 'g']
Example
Let's make the second parameter negative. In this case, the array will be padded from the beginning, not from the end:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
$res = array_pad($arr, -7, 0);
var_dump($res);
?>
Code execution result:
[0, 0, 'a', 'b', 'c', 'd', 'e']
See Also
-
the
array_fill
function,
which fills an array with values -
the
range
function,
which creates an array containing a range of elements