PHP array_pad() function
The array_pad()
function in PHP is used to pad an array to a specified length with a specified value. It can either truncate the array if it's longer than the specified length or extend it by adding the padding value until the specified length is reached.
Syntax:
Parameters:
- $array: The input array that you want to pad.
- $size: The desired size of the array after padding. If this value is greater than the current array size, the array will be padded. If it is less than or equal to the current size, the array will be truncated to this size.
- $value: The value to pad the array with. This value is added to the end of the array if it needs to be extended.
Return Value:
- Returns a new array with the specified padding applied. If the input array is longer than the specified size, the excess elements are discarded.
Example 1: Padding an Array
In this example, we pad an array with the value 0
until its length reaches 5
.
Output:
Here, the original array has a length of 3
. The array_pad()
function adds two 0
s at the end, resulting in an array of length 5
.
Example 2: Truncating an Array
If the specified size is less than or equal to the length of the original array, array_pad()
will truncate the array.
Output:
In this case, the original array has a length of 5
, but we want it to be of length 3
. The last two elements are removed.
Example 3: Negative Size for Padding
You can also use a negative size to pad the array on the left side. The specified size will count from the end of the array.
Output:
In this example, the array is padded with two 0
s at the beginning to make its length 5
. Since the size is negative, it counts from the end.
Example 4: Padding with Different Values
You can use any value to pad the array. For instance, let's pad the array with a string value.
Output:
Here, the array is padded with the string "orange"
until its length reaches 5
.
Practical Usage:
array_pad()
is useful for:- Ensuring that an array has a specific length, particularly when working with fixed-size data structures.
- Preparing data for display or processing where consistent array lengths are required.
- Padding arrays with default values in scenarios like initializing data structures or filling gaps in data.
Summary:
array_pad($array, $size, $value)
pads an array to the specified size with the specified value.- If the specified size is greater than the current size, the array is extended; if it is less than or equal to the current size, the array is truncated.
- You can use negative sizes to pad arrays from the left.
- The function is useful for ensuring uniformity in array sizes in various applications.