PHP array_pad() Function

PHP array_pad() Function

The array_pad() function in PHP pads the array to the given length and value and returns a copy of the array padded to size and value specified by size and value parameter. The padding takes place as follows:

  • If the parameter “size” is positive, then the array is padded on the right, if it's negative then on the left. 
  • If “size” is less than or equal to the size of the array, no padding takes place.

Syntax

array_pad ( array $array , int $size , mixed $value )

Parameter

array(required)- This parameter represents the input arrays to pad.

size(required)- This parameter signifies the new size of the array.

value(required)- This parameter represents the value to pad if the specified array is less than the given size.

Return

This function returns a copy of the array padded to size and value specified by size and value parameter.

Example 1

 

Output

Array
 (
     [0] => 102
     [1] => 10
     [2] => 9
     [3] => 10
 ) 
 After padding the array: 
 Array
 (
     [0] => 102
     [1] => 10
     [2] => 9 
     [3] => 10
     [4] => NA
     [5] => NA
 ) 

Example 2

 

Output

Array
 (
     [0] => 102
     [1] => 10
     [2] => 9
     [3] => 10
 )
 After padding the array:  
 Array
 (
     [0] => NA
     [1] => NA
     [2] => NA
     [3] => 102
     [4] => 10
     [5] => 9 
     [6] => 10
 ) 

Example 3

 

Output

Array
 (
     [0] => Reema
     [1] => Rahul
     [2] => Riya
     [3] => Varun
     [4] => Sukla
     [5] => Amar 
     [6] => Amar
 )