Results 1 to 2 of 2

Thread: [RESOLVED] function, increase a number in variable?

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2008
    Posts
    1,023

    Resolved [RESOLVED] function, increase a number in variable?

    i'm trying to make a number increase inside a function, but i got a problem, the number won't go higher then 1 and i can't figure this out... this is the code i've got so far:

    PHP Code:
    function increase($test)
    {
    global 
    $nr;// global variable
    $nr++;
    echo 
    $test "<br />";
    echo 
    $nr "<br />";
    }

    increase("test1");
    increase("test2"); 
    edit i figured out a solution...
    i just needed to add global $nr; to the code.
    Last edited by Justa Lol; Jan 29th, 2010 at 06:33 PM.

  2. #2
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: [RESOLVED] function, increase a number in variable?

    .. from looking at your code, I have no clue what you're trying to do. you're passing in a string called $test, and then you're incrementing a random variable that doesn't exist ($nr). this variable only exists for as long as your function runs (which is 3 lines of code), and so it goes from not existing, to being initialized when you try to increment it, to then being set to 0 by default, and then being incremented. thus, $nr is equal to 1 when you echo it.

    like, are you trying to make it so that $nr is increased everytime you call the function? this is really the only logical conclusion I can come to. you don't seem to know about variable scope, and so I suggest you first read about it.

    after you've finished reading, you can do something like:

    PHP Code:
    <?php
      $increase_calls 
    0//initialize

      
    function increase($string){
        global 
    $increase_calls//bring $increase_calls into our scope
        
    $increase_calls++;

        echo 
    $increase_calls " => " $string "\n";
      }

      
    increase("test1");
      
    increase("test2");
      
    increase("test3");
    ?>
    the script above should output:
    Code:
    1 => test1
    2 => test2
    3 => test3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width