PHP for loop Exercises: Print alphabet pattern A
13. Alphabet Pattern 'A'
Write a PHP program to print alphabet pattern 'A'.
Visual Presentation:

Sample Solution:
PHP Code:
<?php
// Loop for rows
for ($row = 0; $row <= 7; $row++)
{
// Loop for columns
for ($column = 0; $column <= 7; $column++)
{
// Condition to determine if '*' or ' ' should be printed
if ((($column == 1 or $column == 5) and $row != 0) or (($row == 0 or $row == 3) and ($column > 1 and $column < 5)))
echo "*"; // Print '*' if conditions are met
else
echo " "; // Print ' ' if conditions are not met
}
echo "\n"; // Move to the next line after each row is printed
}
?>
Output:
*** * * * * ***** * * * * * * * *
Explanation:
In the exercise above,
- The code begins with a PHP opening tag <?php.
- It uses a nested loop structure to iterate over rows and columns to create a pattern.
- The outer loop (for ($row = 0; $row <= 7; $row++)) controls the rows of the pattern, iterating from 0 to 7.
- Inside the outer loop, there's another loop (for ($column = 0; $column <= 7; $column++)) that controls the columns by iterating from 0 to 7.
- Within the inner loop, there's a conditional statement that determines whether to print an asterisk ('*') or a space ( ) based on the position of the current row and column indices.
- The condition checks whether the current position corresponds to the desired pattern of asterisks and spaces.
- If the condition is met, an asterisk ('*') is echoed out. Otherwise, a space ( ) is echoed out.
- After printing each row, the code moves to the next line by echoing a newline character ('\n').
- Once all rows and columns are printed according to the pattern, the PHP code ends with a closing PHP tag ?>.
Flowchart :

For more Practice: Solve these Related Problems:
- Write a PHP script to print the letter 'A' using nested loops, ensuring proper spacing to form the letter's shape.
- Write a PHP function to construct the alphabet pattern for 'A' from a given height and then display it line-by-line.
- Write a PHP program to print a scalable 'A' pattern based on user-defined dimensions.
- Write a PHP script to output the 'A' pattern using both echo statements and loops, providing both uppercase and lowercase options.
Go to:
PREV : Floyd Triangle Generation.
NEXT : Alphabet Pattern 'B'.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.