Antonius Carvalho
Antonius Carvalho

Reputation: 1

Need to draw a pyramid in PHP

I need to draw a pyramid in php, only 3 levels will be there and will be at the center of the page i tried a lot but wasn't able to replicate output This is the code i found online and modified a bit (thought of doing the numbering part later once the basic structure was in place)

a side note: was going to try to generate it as an HTML table so that it stayed a bit consistent.

<?php
$height = 3;

echo "<div>";
for($i=1;$i<=$height;$i++){
  for($t = 1;$t <= $height-$i;$t++)
  {
    echo "&nbsp;&nbsp;";
  }
  echo "<center>";
  for($j=1;$j<=$i;$j++)
  {
    // use &nbsp; here to procude space after each asterix
    for ($x=0; $x < 3; $x++) {
      echo "*&nbsp;&nbsp;";
    }
  }
  echo "<br />";
}
echo "</center>";
echo "</div>";
?>

Below is what I am trying to achieve :

The pyramid I need

Upvotes: 0

Views: 351

Answers (1)

Max Zuber
Max Zuber

Reputation: 1229

Let's separate pyramid building and printing:

<?php

$pyramid = [];
$levels_count = 3; // height of the pyramid
$parts_count = 4; // number of subdividing parts
$index = 1; // starting index to numerate vertices
$level = 0;

$columns_count = pow($parts_count, $levels_count - 1);
for ($level = 0; $level < $levels_count; $level++) {
  $level_items_count = pow($parts_count, $level);
  $pyramid[$level] = [
    'colspan' => $columns_count / $level_items_count,
    'items' => range($index, $index + $level_items_count - 1)
  ];
  $index += $level_items_count;
}

// The following code prints the prepared pyramid data
?>
<style>
td {
  text-align: center;
  background-color: #ccc;
}
</style>
<table>
<?php foreach ($pyramid as $row): ?>
  <tr>
  <?php foreach ($row['items'] as $col): ?>
    <td colspan="<?= $row['colspan']; ?>"><?= $col; ?></td>
  <?php endforeach; ?>
  </tr>
<?php endforeach; ?>
</table>

Upvotes: 1

Related Questions