PHP array_pad() Function

Quick summary: The PHP array_pad() function pads an array to the specified length with a given value.

PHP array_pad() Syntax

array_pad(array $array, int $length, mixed $value): array
PHP

PHP array_pad() Basic examples

$array = [1,2];
print_r(array_pad($array, 5, 0));
PHP
Output:
Array ( [0] => 1 [1] => 2 [2] => 0 [3] => 0 [4] => 0 )

Pads the array to length 5 with zeros.

PHP array_pad() Real-world usage

$ids = [10,20];
$ids = array_pad($ids, 4, null);
print_r($ids);
PHP
Output:
Array ( [0] => 10 [1] => 20 [2] =>  [3] =>  )

Ensure fixed-length arrays for data processing.

PHP array_pad() Edge cases

print_r(array_pad([1,2], -5, 0));
PHP
Output:
Array padded on the left

Negative length pads the array to the left.

PHP array_pad() Common mistakes

Expecting original array modification

array_pad() returns a new array.

Incorrect
array_pad($array, 5, 0);
print_r($array);
Correct
$array = array_pad($array, 5, 0);

Assign the result back to a variable.

PHP array_pad() Frequently Asked Questions

What does array_pad() do?

Pads an array to a specified length with a value.

Use case?

Ensure fixed array size.

Syntax?

array_pad(array, size, value).

Common mistake?

Wrong size sign.

Return type?

Array.

Handles negative size?

Pads to the left.

Performance?

Fast.

Safe?

Yes.

Alternative?

Manual loop.

Handles objects?

Yes.

Modifies original?

No.

Best practice?

Validate size first.

PHP array_pad() Related PHP Functions