How to Use str_pad() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `str_pad()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `str_pad()` function is used to pad a string to a certain length with another string. This function is available in PHP 8.1 and 8.2, and it’s commonly used for formatting strings to a specific length. Here’s how you can use `str_pad()` with examples:

Syntax:

<?php
str_pad(string $input, int $pad_length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
?>

Parameters:

1. `$input`: The input string that you want to pad.
2. `$pad_length`: The length of the resulting padded string.
3. `$pad_string`: The string to use for padding. By default, it’s a space.
4. `$pad_type`: Optional. Specifies the type of padding. It can take one of the following values:
– `STR_PAD_RIGHT`: Pad to the right side of the string (default).
– `STR_PAD_LEFT`: Pad to the left side of the string.
– `STR_PAD_BOTH`: Pad on both sides of the string.

Example:

<?php

// Example 1: Pad to the right
$input = "Hello";
$padded = str_pad($input, 10);
echo $padded . "\n"; // Output: "Hello "

// Example 2: Pad to the left with zeros
$input = "123";
$padded = str_pad($input, 5, "0", STR_PAD_LEFT);
echo $padded . "\n"; // Output: "00123"

// Example 3: Pad to both sides
$input = "PHP";
$padded = str_pad($input, 7, "*", STR_PAD_BOTH);
echo $padded . "\n"; // Output: "* PHP *"

// Example 4: Using negative pad length
$input = "World";
$padded = str_pad($input, -10, "-");
echo $padded . "\n"; // Output: "World------"

?>

In these examples, you can see how `str_pad()` works with different parameters to pad the input string to the desired length. It’s a handy function for formatting strings in various contexts.