Backend Development 3 min read

PHP str_pad() Function: Syntax, Parameters, Return Value, and Usage Examples

This article explains PHP's str_pad() function, detailing its syntax, parameter meanings, return value, and provides multiple code examples demonstrating right, left, and both-side padding with custom pad strings, including behavior when pad length is negative or when the pad string length does not evenly divide the required padding.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP str_pad() Function: Syntax, Parameters, Return Value, and Usage Examples

str_pad() pads a string to a specified length using another string.

Signature:

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Description: The function returns the input string padded on the left, right, or both sides to reach the desired length. If $pad_string is omitted, spaces are used; otherwise the provided string is used. If $pad_length is negative or less than or equal to the length of $input , no padding occurs.

Parameters:

$input – the input string.

$pad_length – the target length; negative values result in no padding.

$pad_string – the string used for padding; if its length does not evenly divide the required padding, it may be truncated.

$pad_type – optional; can be STR_PAD_RIGHT , STR_PAD_LEFT , or STR_PAD_BOTH . Default is STR_PAD_RIGHT .

Return value: The padded string.

Examples:

<?php
$input = "Alien";
// Right padding (default) to length 10
echo str_pad($input, 10); // outputs "Alien     "

// Left padding with custom string "-=" to length 10
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // outputs "-=-=-Alien"

// Both-side padding with "_" to length 10
echo str_pad($input, 10, "_", STR_PAD_BOTH); // outputs "__Alien___"

// Padding to length 6 with "___" (right padding by default)
echo str_pad($input, 6, "___"); // outputs "Alien_"
backendphpCode Examplestring paddingphp-functionsstr_pad
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.