Home » PHP

PHP str_pad() function with example

PHP str_pad() function: Here, we are going to learn about the str_pad() function with example in PHP.
Submitted by IncludeHelp, on February 03, 2019

PHP str_pad() function

str_pad() function is used to pad a string with whitespace (default) or any other character/string and returns the padded string.

Syntax:

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

Here,

  • source_string - is the string to be padded.
  • length - is the total number of characters of the targeted string after padding.
  • char/string - to the padding character/string. It's an optional parameter, if we do not pass this parameter, string will be padded with whitespace.
  • padding_type - is the type of padding (it’s an optional parameter), it has following values:
    • STR_PAD_LEFT - To pad the string from left side
    • STR_PAD_RIGHT - To pad the string from right side
    • STR_PAD_BOTH - To pad the string from both sides

Examples:

    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#




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.