Page 1 of 1
Echo and selfcall in functions
Posted: Mon Sep 19, 2005 3:26 am
by HKB
I have this litle test functions:
Code: Select all
function test() {
$i = 2;
echo $i;
if($i < 9) { test(); }
$i = $i + 1;
}
But how do i make echo work and can i call the function in it selfe?
Posted: Mon Sep 19, 2005 4:25 am
by shiznatix
that function will go on forever, never ending loop. that is probably your problem. why not try somtin like
Code: Select all
function test($i)
{
echo $i.'<br>';
if ($i < 9)
test($i++);
}
test(2);
Posted: Mon Sep 19, 2005 5:29 am
by s.dot
You would need to put your $i=$i+1; inside of your loop.
Alternatively, $i=$i+1; is also equal to $i++; (easier to read

)
Code: Select all
$i = 2;
if($i < 9)
{
echo $i;
test();
$i++;
}
And you cannot call the function inside of itself, however you can call its parameters (the stuff in between the ()).
Posted: Mon Sep 19, 2005 7:13 am
by Jenk
This would be more efficient:
Code: Select all
function test() {
for ($i = 2; $i < 9; $i++) {
echo $i;
}
}
Posted: Mon Sep 19, 2005 8:47 am
by shiznatix
scrotaye wrote:And you cannot call the function inside of itself, however you can call its parameters (the stuff in between the ()).
what do you mean? its called recursive function (i think) but i do it all the time
Code: Select all
<?
function test($i)
{
echo $i.'<br>';
if ($i < 9)
test($i+1);
}
test(2);
/*
output:
2
3
4
5
6
7
8
9
*/
?>
strange thing was when it tried test($i++); it did not ++ the $i. hummmm
Posted: Mon Sep 19, 2005 8:49 am
by feyd
$i++ is a post-increment, the increment happens after the variable is returned.
++$i is a pre-increment, the increment happens before the variable is returned.
Posted: Mon Sep 19, 2005 8:55 am
by shiznatix
feyd wrote:$i++ is a post-increment, the increment happens after the variable is returned.
++$i is a pre-increment, the increment happens before the variable is returned.
well ill be damned