PHP str_pad() function with example

str_pad() work is utilized to cushion a string with whitespace (default) or some other character/string and returns the cushioned string.

Syntax:

 str_pad(source_string, length, [char/string], [padding_type]);

Example:

Input: 'Hello"
    Function call: str_pad("Hello", 10, "*");
    Output: "Hello*****"

PHP code:

<?php
	$str = "Hello";

	$padded_str = str_pad($str,10);
	echo($padded_str."#\n");

	$padded_str = str_pad($str,10,' ');
	echo($padded_str."#\n");	

	$padded_str = str_pad($str,10,' ', STR_PAD_RIGHT);
	echo($padded_str."#\n");	

	$padded_str = str_pad($str,10,' ', STR_PAD_LEFT);
	echo($padded_str."#\n");		

	$padded_str = str_pad($str,10,' ', STR_PAD_BOTH);
	echo($padded_str."#\n");			

	$padded_str = str_pad($str,10,'*', STR_PAD_BOTH);
	echo($padded_str."#\n");	

	$padded_str = str_pad($str,10,'TEMP', STR_PAD_BOTH);
	echo($padded_str."#\n");	
?>

Output

Hello     #
Hello     #
Hello     #
     Hello#
  Hello   #
**Hello***#
TEHelloTEM#

Leave a Comment

error: Alert: Content is protected!!