Using array_pad() to Pad an Array to a Specified Length in PHP

This article explains PHP's array_pad() function, detailing its purpose, parameters, return behavior, and provides multiple code examples demonstrating padding arrays to a specified length from both left and right sides, including edge cases.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using array_pad() to Pad an Array to a Specified Length in PHP

The array_pad() function in PHP returns a copy of the input array padded to a length defined by $pad_size using the value $pad_value. If $pad_size is positive, padding is added to the right; if negative, padding is added to the left. No padding occurs when the absolute value of $pad_size is less than or equal to the original array length, and up to 1,048,576 elements can be added in a single call.

Syntax array_pad(array $input, int $pad_size, mixed $pad_value) Parameters

input : The original array to be padded.

pad_size : The desired length of the new array.

pad_value : The value used for padding; applied only when the original array is shorter than $pad_size.

Return value

Returns a new array containing the original elements plus any added padding according to the rules above.

Examples

```php php $input = array(12, 10, 9); // Pad to length 5 on the right with zeros $result = array_pad($input, 5, 0); // $result is array(12, 10, 9, 0, 0) // Pad to length 7 on the left with -1 $result = array_pad($input, -7, -1); // $result is array(-1, -1, -1, -1, 12, 10, 9) // Attempt to pad to length 2 (no padding needed) $result = array_pad($input, 2, "noop"); // $result is array(12, 10, 9) – unchanged ? ```

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPArrayfunctionpadding
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.