Current Location: Home> Latest Articles> PHP Diamond Output Tutorial: How to Generate a Diamond Shape in PHP

PHP Diamond Output Tutorial: How to Generate a Diamond Shape in PHP

M66 2025-09-25

How to Output a Diamond Shape in PHP

Outputting a diamond shape in PHP mainly relies on loop structures and string concatenation. By calculating the middle row of the diamond and using loop controls, we can progressively output the upper half, middle row, and lower half of the diamond.

Step 1: Determine the Middle Row of the Diamond

The size of the diamond is determined by the middle row. Suppose the middle row is defined as $rows.

Step 2: Output the Upper Half of the Diamond

The upper half of the diamond starts from the middle row and proceeds upwards. We can use the PHP str_repeat() function to generate spaces and stars for each row. The loop will run from $rows - 1 and decrease incrementally.


for ($i = $rows - 1; $i >= 1; $i--) {
    $spaces = str_repeat(' ', $i - 1);
    $stars = str_repeat('*', 2 * ($rows - $i) + 1);
    echo $spaces . $stars . "\n";
}

Step 3: Output the Middle Row

The middle row of the diamond consists of $rows * 2 - 1 stars.


$midLine = str_repeat('*', $rows * 2 - 1);
    echo $midLine . "\n";

Step 4: Output the Lower Half of the Diamond

The lower half of the diamond is output similarly to the upper half, but this time starting from row 2 and proceeding downward. The loop will run from 2 and increase incrementally.


for ($i = 2; $i <= $rows; $i++) {
    $spaces = str_repeat(' ', $i - 1);
    $stars = str_repeat('*', 2 * ($rows - $i) + 1);
    echo $spaces . $stars . "\n";
}

Complete Code Example


$rows = 5;  // Set the middle row of the diamond to 5

// Output the upper half of the diamond
for ($i = $rows - 1; $i >= 1; $i--) {
    $spaces = str_repeat(' ', $i - 1);
    $stars = str_repeat('*', 2 * ($rows - $i) + 1);
    echo $spaces . $stars . "\n";
}

// Output the middle row
$midLine = str_repeat('*', $rows * 2 - 1);
echo $midLine . "\n";

// Output the lower half of the diamond
for ($i = 2; $i <= $rows; $i++) {
    $spaces = str_repeat(' ', $i - 1);
    $stars = str_repeat('*', 2 * ($rows - $i) + 1);
    echo $spaces . $stars . "\n";
}

The above code example demonstrates how to use PHP to generate a diamond pattern. You can adjust the value of $rows to change the size of the diamond. By controlling the number of iterations and string concatenation, you can flexibly output various patterns in PHP.