How to Pad an Array in PHP

php



Padding an array means adding elements to an array.

This could adding elements to the beginning of the array or the end of the array.

Below is an example of an array:

(10, 2, 4, 5, 6)

Padding 4 7s to the end of the array would produce:

(10, 2, 4, 5, 6, 7, 7, 7, 7)

So, again, padding an array just means appending new elements to the array.

To pad an array, we use the array_pad PHP function using the following general syntax below:


$array_name= array_pad($array, $size, $value);

where

$array is the original array in which you want to pad elements onto
$size is number of elements that the new padded array will contain in total
$value is the value of the elements which are padded onto the array

So the array_pad function returns an array with $value added to the end of $array until it contains $size elements. If $size is negative, the value is added to the start of the array.

Examples

If we have our orignal array named $numbers and we want to pad onto it 3 10s, the PHP code to do this would be:

$numbers= array(7, 2, 3, 4, 8);
$numbers_2= array_pad($numbers, 8, 10);


PHP Output

7 2 3 4 8 10 10 10

In this example, $size is 8, since we want the total number of elements in our array to be 8 in total when the 3 10s are padded onto it. And $value is 10, since we want to add 10s into the array.



In the example above we padded elements onto the end of the array. In this example, we will pad elements to the beginning of an array. We will use the same array as our last example and pad on the same 3 10s, but this time to the beginning of the array.

The PHP code to do so is:

$numbers= array(7, 2, 3, 4, 8);
$numbers_2= array_pad($numbers, -8, 10);


PHP Output

10 10 10 7 2 3 4 8

In this array, we have almost identifical conditions to our first example. The only difference is the minus sign ("-") in front of the $size. The value of 8 is still the same, since the total number of elements in the array will still be 8, but with the minus sign in front of the 8, the new elements will be padded to the beginning of the array and not to the end of it.


HTML Comment Box is loading comments...