Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator
array_pad

What is the array_pad method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php
communitycreator
array_pad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring