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 :
     *
    **
   ***
  ****
 *****
******
filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


Output:

     *
    **
   ***
  ****
 *****
******


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.