How do You Pad a String to a Certain Length in PHP?

Hello Friends Today, through this tutorial, I will tell you How do You pad a string to a certain length using php the `str_pad()` function With Example? In PHP, you can pad a string to a certain length using the `str_pad()` function. This function allows you to add characters to the beginning or end of a string until it reaches the desired length. Here’s an example of how to use `str_pad()`:

<?php

// Original string
$string = "Hello";

// Pad the string to a length of 10 with spaces added to the right
$padded_string = str_pad($string, 10);
echo "Padded string: '$padded_string'"; // Output: "Padded string: 'Hello '"

// Pad the string to a length of 10 with dashes added to the left
$padded_string_left = str_pad($string, 10, "-", STR_PAD_LEFT);
echo "Padded string (left): '$padded_string_left'"; // Output: "Padded string (left): '-----Hello'"

// Pad the string to a length of 10 with dots added to the right
$padded_string_right = str_pad($string, 10, ".", STR_PAD_RIGHT);
echo "Padded string (right): '$padded_string_right'"; // Output: "Padded string (right): 'Hello.....'"
?>

In this example:

1. The original string is “Hello”.
2. `str_pad()` is used to pad the string to a length of 10 characters.
3. By default, spaces are added to the right if no padding character is specified.
4. You can specify a different padding character and also choose to pad to the left or right by providing the third argument. The fourth argument specifies the padding type, which can be `STR_PAD_LEFT`, `STR_PAD_RIGHT`, or `STR_PAD_BOTH`.