What is the array_pad method in PHP?

The array_pad method can be used to pad elements to the array until the array reaches a specific length.

Syntax


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

Parameters

  • array: Input array
  • length: Output size of the array
  • value: Value to be padded

Points to note

  • If the argument length is positive, then the elements are padded at the end. If it is negative, then the elements are padded at the beginning.

  • If the value of the argument length is less than or equal to the length of the array, then the padding will not happen.

  • The array_pad method pads elements and returns a new array. The original array remains unaffected.

  • If the array has numeric keys, then it will be reassigned based on the padding element position.

Code

<?php
$numbers = [1,2];
printArray($numbers);
// adding 0 at the end
$result = array_pad($numbers, 4, 0);
echo "Padding length: 4 & Padding value: 0 \n";
printArray($result);
// adding 0 at the beginning
$result = array_pad($numbers, -4, 0);
echo "Padding length: -4 & Padding value: 0 \n";
printArray($result);
// no padding
$result = array_pad($numbers, 2, 0);
echo "Padding length: 2 & Padding value: 0 \n";
printArray($result);
function printArray($array){
echo "The array is \n";
print_r($array);
echo "\n";
}
?>

Explanation

In the code above:

  • We create a numbers array.

  • We create a printArray function to print the array.

  • We use the array_pad method to pad elements and make the array a specific length.

Free Resources