PHP » Arrays » array_pad()

Syntax:
array array_pad (array in_array, int pad_size, mixed pad_value)
in_array
The array to be padded.
pad_size
The size of the new padded array. If a negative size is specified, the array will be padded on the left.
pad_value
Value to pad the array with.

Pads an array with a value.

The array_pad() function extends an array to a size by adding the same value a number of times to either end of the array. The function returns a padded copy of the input array.

Examples

Code:
<?php

// 2, 3, 4, 5, 6, 7, 8
$array1 = range(2, 8);
// add some 9's to the end
$padded = array_pad($array1, sizeof($array1) + 4, 9);
// add some 1's to the beginning
$padded = array_pad($padded, -1 * (sizeof($padded) + 4), 1);

foreach ($padded as $element) {
   print "$element ";
}

?>
Output:
1 1 1 1 2 3 4 5 6 7 8 9 9 9 9
Explanation:

The range() function is used to create an array. Then the array_pad() function is used to pad the array on both sides with 1's and 9's.

See Also: