How to do nested loop in descending order? - php

What I want to get with for loop. Something will be like this.
*
**
***
****
*****
****
***
**
*
This thing I want to create right now I have this code.
<?php
$i = 1;
$end = 5;
$star = "*";
for($i; $i <= $end; $i++){
for($b=1; $b <= $i; $b++){
echo $star;
}
if($i == $end){
for($c=1; $c <= $end; $c++ ){
for($d=i; $d >= 2; $d--){
echo $star;
}
echo "<br>";
}
}
};
?>
And it's working fine with
*
**
***
****
*****
But then I need opposite loop first 4 then 3 then 2 then 1...
Where am I going wrong with this?

Just for fun. Try this:
$stars = 1;
for ($i = 0; $i < 9; $i++) {
for ($s = 1; $s <= $stars; $s++) {
echo "*";
}
echo "\n";
$stars += ($i<4)?1:-1;
}
And, for even more fun, one with just one for loop:
$stars = 0;
$starctr = 0;
for ($i = 0; $i < 25; $i++) {
echo "*";
if ($stars == $starctr) {
echo "\n";
$stars += ($i<14)?1:-1;
$starctr = 0;
} else {
$starctr++;
}
}

Can using nested for loop. Example:
$n = 5;
for($i = 1; $i <= $n; $i++){
for($j = 1; $j <= $i; $j++){
echo '*';
}
echo '<br />';
}
for($i = $n-1; $i >= 1; $i--){
for($j = $i; $j >= 1; $j--){
echo '*';
}
echo '<br />';
}
Another technique using array_fill(), array_map(), array_reverse()
$n = 5; $arr = array();
for($i = 1; $i <= $n; $i++){
$arr[] = array_fill(0, $i, '*');
}
array_map(function($v){echo join('', $v) . '</br>';},$arr);
unset($arr[count($arr) - 1]); //remove last index value
array_map(function($v){echo join('', $v) . '</br>';},array_reverse($arr));

<?php
for($i=0;$i<=6;$i++){
for($k=6;$k>=$i;$k--){
echo " ";
}
for($j=1;$j<=$i;$j++){
echo "* ";
}
echo "<br>";
}
for($i=5;$i>=1;$i--){
for($k=6;$k>=$i;$k--){
echo " ";
}
for($j=1;$j<=$i;$j++){
echo "* ";
}
echo "<br>";
}
?>

This can be achieved with only 2 for loops.
$offset = 1;
for ($i = 1; $i > 0; $i += $offset)
{
for($j = 1; $j <= $i; $j++){
echo '*';
}
echo '<br />';
if ($i === 5)
$offset = -1;
}

<?php
$i = 1;
$end = 5;
$star = "*";
for($i; $i <= $end; $i++){
for($b=1; $b <= $i; $b++){
echo $star;
}
};
for($c=$send; $c>=2; $c-- ){
for($d=$end; $d >= 2; $d--){
echo $star;
}
echo "<br>";
};
?>

Using a single for loop:
$end = 5;
$out = array();
for ($i=0;$i<$end;++$i)
{
$out[] = str_repeat('*', $i+1);
}
echo implode(PHP_EOL, $out).PHP_EOL;
array_pop($out);
$out = array_reverse($out);//remove last ****** <-- only one line with 5 stars
echo implode(PHP_EOL, $out).PHP_EOL;
Replace PHP_EOL with <br> if you want to, but this is the least loopy way to write this code I can think of
live demo

Here's a recursive attempt:
function ladder($n, $counter=1, &$acc=array())
{
if ($counter == ($n*2)) {
return implode($acc);
}
if ($counter <= $n) {
$acc[$counter] = str_repeat('*', $counter) . "\n";
$counter++;
}
if ($counter > $n) {
$diff = (int) $n-$counter;
$acc[$counter] = str_repeat('*', $n+$diff) . "\n";
$counter++;
}
return ladder($n, $counter, $acc);
}
print_r(ladder(5));

Related

Write a PHP code to print following number pattern

Write a PHP code to print following number pattern:
147
258
369
I am trying like this but its shows me shows below. how to convert column to row pattern.
<?php
$num = "";
for($i=1;$i<=9;$i++) {
$num .= $i;
if($i%3==0){
$num .="<br />";
}
}
echo $num;
?>
please help me
You need to use for loop inside for loop to achieve this. Below is the code
$num = "";
for( $i = 1; $i <= 3; $i++ ) {
for( $j = 0; $j <= 2; $j++) {
$k = $i + ( $j * 3 );
$num .= $k;
}
$num .= "<br />";
}
echo $num;
Here is another way to get this output.
for($i = 1; $i <= 3; $i++) {
$print = $i;
for($j = 1; $j <= 3; $j++) {
echo $print;
$print = $print + 3;
}
echo "<br />";
}

how to write a nested php loop that draws an image with few lines of code?

How best can i solve this with less code as possible below is the problem
*****
****x
***xx
**xxx
*****
**xxx
***xx
****x
*****
this is my code that i want to improve:
<?php
for ($i=0; $i < 5 ; $i++) {
if($i >= 1 & ($i <= 3))
{
for ($t=0; $t < 5-$i ; $t++)
echo "*";
for ($t=0; $t < $i ; $t++)
echo "x";
}
else
for ($j=0; $j < 5 ; $j++)
echo "*";
echo "<br/>";
}
for ($f=1; $f < 5 ; $f++) {
for ($j=0; $j < $f+1; $j++)
echo "*";
for ($v=3; $v>= $f; $v--)
echo "x";
echo "<br/>";
}
?>
To create string with repeated symbols you can use str_repeat. Using this function your code can be simplified to:
$num = 5;
for ($i = $num; $i > 1; $i--) {
echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}
echo str_repeat('*', $num) . PHP_EOL;
for ($i = 2; $i <= $num; $i++) {
echo str_repeat('*', $i) . str_repeat('x', $num - $i) . PHP_EOL;
}
Even if you cannot use php core functions, you can write you own function to create same results as str_repeat:
function createLine($starsCount, $XCount) {
$result = '';
for ($i = 0; $i < $starsCount; $i++) {
$result .= '*';
}
for ($i = 0; $i < $XCount; $i++) {
$result .= 'x';
}
return $result;
}
And rewrite code as:
$num = 5;
for ($i = $num; $i > 1; $i--) {
echo createLine($i, $num - $i) . PHP_EOL;
}
echo createLine($num, 0) . PHP_EOL;
for ($i = 2; $i <= $num; $i++) {
echo createLine($i, $num - $i) . PHP_EOL;
}

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!
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>";
?>
I used the code below without using a table to make a diamond shape.
<div style="text-align: center">
<?php
$n = 8;
if($n === 1){ die("input must be greater than 1"); }
$nn = ($n * 2);
$m = (ceil($nn / 2) + 1);
$temp = 0;
for($x = 1; $x <= $nn; $x++){
$temp = (($x < $m) ? ($temp + 1) : ($temp - 1));
$total = ($temp > 1 ? ((2 * $temp) - 1) : $temp);
echo nl2br(str_repeat('* ', $total) . "\r\n");
}
?>
I used the code below.
<div style="text-align: center">
<?php
$n = 8;
if($n === 1){ die("input must be greater than 1"); }
$nn = ($n * 2);
$m = (ceil($nn / 2) + 1);
$temp = 0;
for($x = 1; $x <= $nn; $x++){
$temp = (($x < $m) ? ($temp + 1) : ($temp - 1));
$total = ($temp > 1 ? ((2 * $temp) - 1) : $temp);
echo nl2br(str_repeat('* ', $total) . "\r\n");
}
?>
<?php
for($i=0;$i<=5;$i++){
for($j=5;$j>=$i;$j--){
echo ' ';
}
for($k=0;$k<=$i;$k++){
echo '*';
}
echo '<br />';
}
for($i=0;$i<=4;$i++){
for($k=0;$k<=$i+1;$k++){
echo ' ';
}
for($j=4;$j>=$i;$j--){
echo '*';
}
echo '<br />';
}
?>

print number vertically and grouping it

I am trying to print number vertically and it must be in group
here is my code
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
for ($j = $i; $j <= 24; $j = $j + $rows) {
$count++;
if($count>$nums){
break;
}
echo "<div class='fleft'>$count</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
out of above
but i want output like for the first column
and next group number will start from where first group number end. in this case next group start from 25
please ask if any doubt
$nums = 105;
$rows = 8;
$colsize = 3;
$col = floor($nums / $rows);
$group = floor($col / $colsize);
$count = 0;
$groupsize = $rows * $colsize;
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
$modulo = 0;
$correction = 0;
$rest = $nums - $count;
if ($rest < $groupsize) {
$empty = $groupsize - $rest;
$correction = floor($empty / $colsize);
$modulo = $empty % $colsize;
}
for ($i = 1; $i <= $rows; $i++) {
$colind = 0;
for ($j = $i; $j <= $groupsize; $j = $j + $rows) {
$count++;
if ($count > $nums) {
break;
}
$val = $j + ($g * $groupsize);
$val -= $colind * $correction;
$modcor = $colind - ($colsize - $modulo);
if ( $modcor > 0 ) {
$val -= $modcor;
}
echo "<div class='fleft'>" . $val . "</div>";
$colind++;
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
This works:
Also, you can change number of digits, columns or size of column
for($group = 0; $group < 3; $group++){
for($row =1 ; $row <= 8; $row++){
for($col = 0; $col <= 2; $col++){
echo ($group*24)+ $row + 8 * $col; echo " ";
}
echo "\n";
}
}
This code will print the number in the requested format. You need to modify according to your need.
may be i am mad , made a simple alter .... try this
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$letCounter=0; //added a counter
for ($g = 0; $g <= $group; $g++) {
echo "<div class='group'>";
for ($i = 1; $i <= $rows; $i++) {
$letCounter=0; //reset counter on each loop
for ($j = $i; $j <= 24; $j = $j + $rows)
{
$count++;
if($count>$nums)
{break;}
//made an alter in the below line , some math :)
echo "<div class='fleft'>".($letCounter++ * $rows +$i)."</div>";
}
echo "<div class='clear'></div>";
}
echo "</div>";
}
Thanks !
This May work
$nums = 105;
$rows = 8;
$col = floor($nums / $rows);
$group = floor($col / 3);
$count = 0;
$flag = true;
for($c=1;$c<=$col;$c++)
{
if($c%$group== 1)
{
echo "Group Start";
$flag = false;
}
for ($i = 1; $i <= $rows; $i++) {
$count++;
echo "<div class='fleft'>$count</div>";
echo "<div class='clear'></div>";
}
echo "Line End";
if($c%$group == 2&& $flag)// Check here for your requirement
echo "Group End </br>";
$flag = true;
}

Print pyramid pattern

1
1 2 1
1 2 3 2 1
1 2 1
1
$newline = "\r\n";
$prnt = '*';
$nos = 3;
for($i = 1; $i <= 2; $i++)
{
for($s = $nos; $s >= 1; $s--)
{
echo " ";echo " ";echo " ";
}
for($j = 1; $j <= $i; $j++)
{
echo $j;echo " ";
}
$m = 2;
for($k = 1; $k <= ($i - 1); $k++)
{
echo $k;echo " ";
}
echo '<br />';
$nos--;
}
$nos = 1;
for($i = 3; $i >= 1; $i--)
{
for ($s = $nos; $s >= 1; $s--) {
echo " ";echo " ";echo " ";
}
for($j = 1; $j <= $i; $j++)
{
echo $j;echo " ";
}
for($k = 1; $k <= ($i - 1); $k++)
{
echo $k;echo " ";
}
$nos++;
echo '<br />';//printf("\n");
}
i got output
1
1 2 1
1 2 3 1 2
1 2 1
1
am not able to print space when i use echo ' '; so i used echo " "; but i dont want to use echo " "; plz resolve this issue.
I am having problem creating above program but somewhere missing a value may be need apply some condition over there . Please see my code.
Printing multiple spaces in straight HTML isn't allowed because of how it must be rendered.
If you want to print exactly - whitespaces included - just wrap your code with a <pre/> tag.
<pre>Spacing will be literal.</pre>
You could also format with the white-space CSS property by setting it to pre.
.spaces {
white-space: pre;
}
<div class="spaces">Spacing will be literal.</div>
This is a fun little algorithm. Here's a recursive solution in PHP. I wrap it in <PRE> tag so that I can use spaces and new lines "\n".
<pre>
<?php
function printPyramid($height) {
// initialize
$size = ($height * 2) - 1;
$half = $size / 2;
$arr = Array();
for($r = 0; $r < $size; $r++) {
$arr[] = array();
for($c = 0; $c < $size; $c++) {
$arr[$r][] = "";
}
}
$arr[$half][$half] = $height;
// recursively build, pass array as reference "&"
pyramidRec($arr, $half, $half, $size);
// print
for($r = 0; $r < $size; $r++) {
for($c = 0; $c < $size; $c++) {
if(empty($arr[$r][$c]))
echo " ";
else if(strlen($arr[$r][$c]) == 1)
echo "{$arr[$r][$c]} ";
else
echo $arr[$r][$c];
}
echo "\n";
}
}
function pyramidRec(&$arr, $r, $c, $size) {
$val = $arr[$r][$c];
$newVal = $val - 1;
if($newVal == 0)
return;
// up
if($r - 1 >= 0 && empty($arr[$r-1][$c])) {
$arr[$r-1][$c] = $newVal;
pyramidRec($arr, $r-1, $c, $size);
}
// down
if($r + 1 < $size && empty($arr[$r+1][$c])) {
$arr[$r+1][$c] = $newVal;
pyramidRec($arr, $r+1, $c, $size);
}
// left
if($c - 1 >= 0 && empty($arr[$r][$c-1])) {
$arr[$r][$c-1] = $newVal;
pyramidRec($arr, $r, $c-1, $size);
}
// right
if($c + 1 < $size && empty($arr[$r][$c+1])) {
$arr[$r][$c+1] = $newVal;
pyramidRec($arr, $r, $c+1, $size);
}
}
printPyramid(5);
?>
</pre>

Categories