PHP array_pad() Function
The PHP array_pad() function returns a copy of the array padded to the specified size with a specified value. If size is positive then the array is padded on the right, if it is negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place.
Syntax
array_pad(array, size, value)
Parameters
array |
Required. Specify the initial array of values to pad. |
size |
Required. Specify new size of the array. |
value |
Required. Specify the value to pad if array is less than size. |
Return Value
Returns a copy of the array padded to the specified size with a specified value. If size is positive then the array is padded on the right, if it is negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place.
Exceptions
NA.
Example:
The example below shows the usage of array_pad() function.
<?php $Arr = array(10, 20, 30); //padding the array $result1 = array_pad($Arr, 5, 100); $result2 = array_pad($Arr, -5, 100); //displaying the result echo "The original array:\n"; print_r($Arr); echo "\n"; echo "The right padded array:\n"; print_r($result1); echo "\n"; echo "The left padded array:\n"; print_r($result2); ?>
The output of the above code will be:
The original array: Array ( [0] => 10 [1] => 20 [2] => 30 ) The right padded array: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 100 [4] => 100 ) The left padded array: Array ( [0] => 100 [1] => 100 [2] => 10 [3] => 20 [4] => 30 )
Example:
Consider one more example where the array_pad() function is used with associative arrays.
<?php $Arr = array("a"=>"Red", "b"=>"Green", "c"=>"Blue"); //padding the array $result = array_pad($Arr, 5, "NoColor"); //displaying the result echo "The original array:\n"; print_r($Arr); echo "\n"; echo "The padded array:\n"; print_r($result); ?>
The output of the above code will be:
The original array: Array ( [a] => Red [b] => Green [c] => Blue ) The padded array: Array ( [a] => Red [b] => Green [c] => Blue [0] => NoColor [1] => NoColor )
❮ PHP Array Reference