PHP str_pad to print string patterns
Last Updated :
01 Apr, 2018
str_pad:
Pad a string to a certain length with another string.
Syntax:- str_pad (input, pad_length, pad_string_value, pad_type)
It returns the padded string.
Parameters Description
input:-The input string.
pad_length:-If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input is returned.
pad_string_input:-The pad_string may be truncated if the required number of padding characters can’t be evenly divided by the pad_string’s length.
pad_type:-Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
Print simple patterns like below using single line of code under loop.
Examples:
Input : 5
Output :
*
**
***
****
*****
Input : 6
Output :
*
**
***
****
*****
******
<?php
function generatePattern( $n )
{
$str = "" ;
for ( $i =0 ; $i < $n ; $i ++)
{
$str .= "*" ;
echo str_pad ( $str , $n , " " , STR_PAD_LEFT), "\n" ;
}
}
$n = 6;
generatePattern( $n );
?>
|
Output:
*
**
***
****
*****
******
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...