PHP str_pad to print string patterns
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// PHP program to print a pattern using only// one loop. function generatePattern($n){ // Initialize the string $str = ""; // Iterate for n lines for ($i=0 ; $i<$n ; $i++) { // Concatenate the string $str .= "*"; echo str_pad($str, $n, " ", STR_PAD_LEFT), "\n"; }} // Driver code$n = 6;generatePattern($n);?> |
Output:
*
**
***
****
*****
******


