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.

Edited by ignace
code tags plus indentation
Link to comment
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";
}
Edited by ignace
Link to comment
Share on other sites

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

Edited by cyberRobot
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.