PHP str_pad() function with example

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#

Recent Posts

error: Alert: Content is protected!!