|
-
Jan 29th, 2010, 06:23 PM
#1
Thread Starter
Fanatic Member
[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.
-
Jan 29th, 2010, 06:35 PM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|