Kenny Kenny - 8 days ago 6
HTML Question

How to do a Diamond Pattern / Shape (asterisks) inside a table? (html + php)

I have to make a diamond-shaped asterisk using for loop, inside a table. It has to have "blank"

<td>
spaces before and after the asterisks to move and make it look centered, so it looks like a diamond. How do I do that? (I used PHP inside an HTML code.)

Code without the
<tr>
and
<td>
tags, it looked like a diamond because it was center aligned:

<center>
<?php
echo "<table border = 1>";

// loop for the pyramid

for($i = 1; $i <= 10; $i += 2) {
for($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br />";
}

// loop for the inverted pyramid, so it looks like a diamond

for($i = 7; $i >= 1; $i -= 2) {
for($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br />";
}

echo "</table>";
?>
</center>


Code with the
<tr>
and
<td>
tags, need "spaces" for it to look like it's center aligned:

<?php
echo "<table border = 1>";

// loop for the pyramid

echo "<tr>";
for($i = 1; $i <= 10; $i += 2) {
echo "<tr>";
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
echo "</tr>";
}
echo "</tr>";

// loop for the inverted pyramid, so it looks like a diamond

for($i = 7; $i >= 1; $i -= 2) {
echo "<tr>";
for($j = 1; $j <= $i; $j++) {
echo "<td>* </td>";
}
echo "<br />";
echo "</tr>";
}

echo "</table>";
?>


Please help! Thanks in advance!

Answer

Here is new Code with your solution. I have added logic to put blank td forward and backward to *

<?php
echo "<table border = 1>";

    // loop for the pyramid

    echo "<tr>";
    $max = $initAmount = 10;
            for($i = 1; $i <= $initAmount; $i += 2) {
                $max = $max -2;

                    $halfTD = (int)$max/2;
            echo "<tr>";
            for($b = 1; $b <= $halfTD; $b++){
                        echo "<td></td>";
                    }
                for($j = 1; $j <= $i; $j++) {


                    echo "<td>* </td>";
                }
                for($b = 1; $b <= $halfTD; $b++){
                        echo "<td></td>";
                    }
            echo "</tr>";
        }
    echo "</tr>";

    // loop for the inverted pyramid, so it looks like a diamond
$max = $initAmount = 10;
    for($i = 7; $i >= 1; $i -= 2) {
        $max = $max -2;
        $diff = $initAmount - $max;
        $blankTd = $diff/2;

    echo "<tr>";
        for($b = 1 ; $b <= $blankTd; $b++){
            echo "<td></td>";
        }
        for($j = 1; $j <= $i; $j++) {
            echo "<td>* </td>";
        }   
        for($b = 1 ; $b <= $blankTd; $b++){
            echo "<td></td>";
        }
    echo "</tr>";
    }

echo "</table>";
?>
Comments