str_pad() function in PHP


The str_pad() function is used to pad a string to a new length. It returns the padded string.

Syntax

str_pad(str, len, pad_str, pad_type)

Parameters

  • str − The string to pad

  • len − The new string length

  • pad_str − The string to use for padding

  • pad_type − The side to pad the string.

  • The following are the possible values −

    • STR_PAD_BOTH  − Pad to both sides of the string. If not an even number, the right side gets the extra padding

    • STR_PAD_LEFT  − Pad to the left side of the string

    • STR_PAD_RIGHT  − Pad to the right side of the string.

Return

The str_pad() function returns the padded string.

Example

The following is an example −

 Live Demo

<?php
$s = "Welcome";
echo str_pad($s,10,"$",STR_PAD_LEFT);
?>

Output

$$$Welcome

Example

The following is an example −

 Live Demo

<?php
$s = "Welcome";
echo str_pad($s,10,"$",STR_PAD_RIGHT);
?>

Output

Welcome$$$

Example

The following is an example −

 Live Demo

<?php
$s = "Welcome";
echo str_pad($s,10,"$",STR_PAD_BOTH);
?>

Output

$Welcome$$

Updated on: 24-Jun-2020

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements