I need to create a pyramid using asterisks. I specify a value which becomes the base of the pyramid. The base contains as much asterisks as the value specified and the pyram
From what I understand, what you are looking for is an Odd numbered pyramid, i.e. the number of * in each row is as per odd number series, like 1,3,5,7. If you wish to include "if-else" statements then you can go with the above answered loops, but if you only wish to use "for" loops, then you can use the following code:
<?php
$x=1;
for($i=1;$i<7;$i++)
{
for($j=7;$j>$i;$j--)
{
echo ' ';
}
for($k=1;$k<=$x;$k++)
{
echo '*';
}
$x=$x+2;
echo "<br/>";
}
?>
Just make it simpler:
function create_pyramid($limit) {
for($row = 1; $row < $limit; $row ++) {
$stars = str_repeat('*', ($row - 1) * 2 + 1);
$space = str_repeat(' ', $limit - $row);
echo $space . $stars . '<br/>';
}
}
echo "<pre>" ;
create_pyramid(10);
<?php
ini_set('display_errors', 1);
/**
* Here is my solution for printing the pyramid using a class
*/
class pyramid
{
function __construct($rows)
{
for ($k=1; $k <= $rows ; $k++) {
$this->space($rows,$k);
$this->left($k);
$this->right($k);
echo "<br>";
}
}
public function left($k)
{
for ($i=1; $i < $k ; $i++) {
echo $i;
}
}
public function right($i)
{
for ($j=$i; $j >= 1 ; $j--) {
echo $j;
}
}
public function space($rows,$k)
{
for ($i=$rows-$k; $i > 0 ; $i--) {
echo " ";
}
}
}
$pyramid = new pyramid(5);
?>
<style type="text/css">
body{
font-family: monospace;
font-size: 24px;
}
</style>
<?php
$n=9;
for($i=0; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
echo " ";
for($k=1; $k<=$n-$i; $k++)
echo $k;
for($j=($k-2); $j>0; $j--)
echo $j;
for($k=1; $k<=$i; $k++)
echo " ";
echo "</br>";
}
?>
<?php
$l=5;
for ($i=1; $i <=5; $i++) {
for ($k=1; $k < $l ; $k++) {
echo ' ';
}
for ($j=0; $j<$i; $j++) {
echo '*';
}
$l--;
echo "<br>";
}
?>
function create_row($num, $limit) {
$append = '';
if($limit > $num && ($limit - $i) % 2 == 0) {
$append .= '-';
}
$stars = str_repeat('*', $num);
$ap_len = floor(($limit - $num) / 2);
$prepend = str_repeat('-', $ap_len);
$append .= str_repeat('-', $ap_len);
return $prepend . $stars . $append;
}
function create_pyramid($limit){
if ($limit > 0){
$no_last = false;
for($i = 1; $i <= $limit; $i += 2) {
print create_row($i, $limit) . PHP_EOL;
if($i == $limit) {
$no_last = true;
}
}
if(!$no_last) {
print create_row($limit, $limit) . PHP_EOL;
}
}
}
create_pyramid(10);