To print an Hourglass Pattern in PHP, we can use loops and string manipulation to achieve the desired pattern.
In this example,
printHourglass
that takes the desired number of rows $n
as a parameter.$n
to 1 and the inner loops control the spaces and stars in each row.<?php
function printHourglass($n) {
for ($i = $n; $i >= 1; $i--) {
$spaces = str_repeat(' ', $n - $i);
$stars = str_repeat('*', 2 * $i - 1);
echo $spaces . $stars . "\n";
}
for ($i = 2; $i <= $n; $i++) {
$spaces = str_repeat(' ', $n - $i);
$stars = str_repeat('*', 2 * $i - 1);
echo $spaces . $stars . "\n";
}
}
// Example usage
printHourglass(5);
?>
********* ******* ***** *** * *** ***** ******* *********
In this tutorial, we learned How to print Hour Glass Pattern in PHP language with well detailed examples.