Page 1 of 1

Add one to number each time it appears

Posted: Wed Sep 12, 2007 3:06 pm
by elinews
I want to make a numeric variable (starting at 0) have 1 added to it each time it appears.

How can I do this?

THANKS!

Posted: Wed Sep 12, 2007 3:12 pm
by onion2k
Rather than using a variable, use a function.

Code: Select all

function counter($counter=0) {
  static $counter;
  return $counter++;
}

for ($x=0;$x<10;$x++) {
  echo counter();
}

echo counter();
echo counter()+5;
echo counter()+5;

Posted: Wed Sep 12, 2007 3:50 pm
by elinews
onion2k wrote:Rather than using a variable, use a function.

Code: Select all

function counter($counter=0) {
  static $counter;
  return $counter++;
}

for ($x=0;$x<10;$x++) {
  echo counter();
}

echo counter();
echo counter()+5;
echo counter()+5;
Awesome. Thanks. What's causing this gobbledegook to come out though? :

123456789101617

Posted: Wed Sep 12, 2007 3:51 pm
by feyd
Not having a carriage return after the number echo out.

Posted: Wed Sep 12, 2007 4:59 pm
by elinews
feyd wrote:Not having a carriage return after the number echo out.
Ha ha. I'm really not experienced with functions() Is there a tutorial or something that could show me how to do the carraige return?

Thanks

Posted: Wed Sep 12, 2007 5:12 pm
by feyd
it has less to do with functions and more to do with simple parameters to echo(). Try the PHP_EOL constant for example.

Posted: Wed Sep 12, 2007 5:25 pm
by superdezign
Or '<br />' to make it more obvious in the browser.

Posted: Thu Sep 13, 2007 4:54 pm
by elinews
I'm really lost. If it's no trouble could someone show me how this is done?

Posted: Thu Sep 13, 2007 8:06 pm
by Stryks
I believe the suggestion is ...

Code: Select all

for ($x=0;$x<10;$x++) {
  echo counter() . '<br />';
}
It just inserts a line break after each number.

Or are you asking something else?

Posted: Thu Sep 13, 2007 8:33 pm
by elinews
Stryks wrote:I believe the suggestion is ...

Code: Select all

for ($x=0;$x<10;$x++) {
  echo counter() . '<br />';
}
It just inserts a line break after each number.

Or are you asking something else?
Ah I'm starting to understand this. Thank you - you just helped me solve my problem.