📌 PHP array_pad()
Function Tutorial with Examples
The array_pad()
function in PHP is used to pad an array to a specified length with a specified value. If the array has fewer elements than the target size, it fills the rest with the value you provide.
📌 Syntax:
Parameters:
-
$array
→ The original array you want to pad. -
$size
→ The target size of the new array.-
Positive value: Pads to the end (right).
-
Negative value: Pads to the beginning (left).
-
-
$value
→ The value to use for padding.
📌 How it Works:
-
If the array is already equal to or larger than the desired size, no padding is added.
-
If it's smaller, the function adds the specified value until the array reaches the target size.
-
It returns a new array — the original remains unchanged.
📌 Example 1: Pad Array to the Right
Output:
📌 Example 2: Pad Array to the Left
Output:
📌 Example 3: No Padding Needed
Output:
📌 Use Cases:
✅ Ensuring an array has a minimum length
✅ Filling empty positions in an array with placeholder values
✅ Creating fixed-length arrays for layouts or calculations
📌 Final Thoughts:
The array_pad()
function is a handy tool for adjusting array sizes and filling gaps with any default value. It’s particularly useful for working with form data, table rows, or fixed-size structures where you need to guarantee a consistent number of elements.
📌 Official Documentation:
For more details, visit:
👉 PHP array_pad()
Documentation
Comments
Post a Comment