To print a Hollow Diamond Pattern in PHP, we use nested loops to manage spaces and stars.
In this example,
<?php
// Print Hollow Diamond Pattern in PHP
function printHollowDiamond($numRows) {
$diamond = [];
for ($row = 1; $row <= $numRows; $row++) {
$pattern = '';
for ($space = 1; $space <= $numRows - $row; $space++) {
$pattern .= ' ';
}
for ($star = 1; $star <= 2 * $row - 1; $star++) {
if ($star === 1 || $star === 2 * $row - 1) {
$pattern .= '*';
} else {
$pattern .= ' ';
}
}
$diamond[] = $pattern;
}
for ($row = $numRows - 1; $row >= 1; $row--) {
$pattern = '';
for ($space = 1; $space <= $numRows - $row; $space++) {
$pattern .= ' ';
}
for ($star = 1; $star <= 2 * $row - 1; $star++) {
if ($star === 1 || $star === 2 * $row - 1) {
$pattern .= '*';
} else {
$pattern .= ' ';
}
}
$diamond[] = $pattern;
}
return implode("\n", $diamond);
}
echo printHollowDiamond(5);
?>
* * * * * * * * * * * * * * * *
In this tutorial, we learned How to print Hollow Diamond Pattern in PHP language with well detailed examples.