Jump to content

More questions from a beginner


Loose_Goose

Recommended Posts

Please be patient with me as I am only a beginner.  I am trying to learn this on my own using online tutorials.  I have written the following code;

 

<?php
$counter=30;
while ($counter>-1)
{
  echo $counter;
  $counter=$counter+-1;
  if ($counter==0){
    while ($counter<30)
    {
      echo $counter++;
      $counter=$counter++;
    }
  }
}
?>
 

It runs continuously.  I want it to count down to zero, up to 30 again, and then stop.  I also want to know how I can get each number to appear on a separate line instead of all the numbers appearing on the same line.

Link to comment
https://forums.phpfreaks.com/topic/280651-more-questions-from-a-beginner/
Share on other sites

// count down from 30 to 0
for ($i = 30; $i >= 0; $i = $i - 1 /* long version to better understand what happens <=> $i -= 1 <=> $i-- */) {
echo $i, '<br>', "\n";
}

// count up from 0 to 30
for ($i = 0; $i <= 30; $i = $i + 1 /* long version to better understand what happens <=> $i += 1 <=> $i++ */) {
echo $i, '<br>', "\n";
}

If you don't need a loop, you could also do something like this:

<?php
$numbers = range(1, 30);
print implode('<br>', $numbers);
print '<br>';
$numbers = array_reverse($numbers);
print implode('<br>', $numbers);
?>

An example of using range() in a foreach loop can be found here:

http://php.net/manual/en/function.range.php

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.