Home > Blockchain >  How can i remove things in a for loop?
How can i remove things in a for loop?

Time:06-03

so thats my code and i know i have to put a for loop inside a for loop to get what i want.(very new to programming so dont blame me lmao)

   <?php include('includes/header.php'); ?>

<div >
    <?php
    for ($i=0; $i<=10; $i  ) {
        for ($j=0; $j<=10; $j  ) {

            echo '*';
        }
        echo '<br />';
    }

    for ($i = 10;$i >= 10; $i--){

        for ($i = $i; $i >=0; $i--){

            echo "*";
        }
        echo "<br />";
    }
    ?>
</div>
<?php include('includes/footer.php'); ?>
***********
***********
***********
***********
***********
***********
***********
***********
***********
***********
***********

thats what it looks like but i want it like that:

***********
*         *
*         *
*         *
*         *
*         *
*         *
*         *
*         *
*         *
*         *
***********

Can someone tell me how i can make it to look like this?

CodePudding user response:

for($i=0; $i<=10; $i  ) {
   for($j=0; $j<=10; $j  ) {
      if($i==0||$i==10) {
         echo '*';
      }
      else {
        if($j==0||$j==10) {
           echo '*';
        }
        else {
            echo ' ';
        }
     }
   }
   echo '<br />';
}

or if you don't care about readabilty,

for($i=0; $i<=10; $i  ) {
    for($j=0; $j<=10; $j  ) {
        echo  $i==0||$i==10||$j==0||$j==10 ? '*' :' ';
    }
    echo '<br />';
}

should also do the job.

CodePudding user response:

Only one nested loop is enough. If the current row is between first and last(both exclusive) and if the current column is between first and last(both exclusive), then print a space, else print the asterisk(*).

Snippet:

<?php

$N = 10;

for ($i = 1; $i <= $N; $i  ) {
    for ($j = 1; $j <= $N; $j  ) {
        echo $j > 1 && $j < $N && $i > 1 && $i < $N ? ' ' : '*';
    }
    echo PHP_EOL; // or echo "<br/>";
}

Online Demo

  •  Tags:  
  • php
  • Related