PHP str_pad Function: Usage, Parameters, and Examples
This article explains the PHP str_pad function, detailing its syntax, parameter meanings, return value, and provides multiple code examples demonstrating right, left, and both-side padding with custom strings.
The PHP str_pad function pads a string to a specified length using a given padding string and direction.
Syntax: string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
It returns the padded string; if $pad_length is less than or equal to the length of $input , no padding occurs. The optional $pad_string defaults to a space, and $pad_type can be STR_PAD_RIGHT , STR_PAD_LEFT , or STR_PAD_BOTH .
Parameters:
input : the original string.
pad_length : the target length; negative values or values not greater than the input length result in no padding.
pad_string : the string used for padding; if its length does not divide evenly into the required padding, it may be truncated.
pad_type : direction of padding (right, left, both); defaults to STR_PAD_RIGHT .
Example usage:
<?php
$input = "Alien";
echo str_pad($input, 10); // outputs "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // outputs "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // outputs "__Alien___"
echo str_pad($input, 6, "___"); // outputs "Alien_"Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.