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.
The size of the diamond is determined by the middle row. Suppose the middle row is defined as $rows.
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";
}
The middle row of the diamond consists of $rows * 2 - 1 stars.
$midLine = str_repeat('*', $rows * 2 - 1);
echo $midLine . "\n";
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";
}
$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.