How to Count Iterations of a PHP Function

I find myself having to do this all the time! I need to know how many times a function is running and for some strange reason, I almost never remember how to do it correctly. That's why I am posting this simple trick on my blog, so others can find it easily and so I can look at how I did it next time I need to do it again!

Here's a simple example to illustrate the need here:

<?php
function runMe(){

$i = 0;

$i++;

echo "$i<br>";

}

//If you were to execute the above function in a loop like this:

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

runMe();

}
?>

The output of the above would be:

1
1
1
1
1
1
1
1
1
1

Not what you wanted? or expected? Often we need it to output something like this instead:

1
2
3
4
5
6
7
8
9...

Static Variable to the Rescue

In comes what is know in PHP as Static Variables.  Here's a quick code example that should make you understand how they work:

<?php
function countRuns(){

static $c = 0;

$c++;

echo "$c<br />";

}

//Then, Executing the countRuns function in a for loop will increment the number printed ea. time:

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

countRuns();

}
?>

If you were to run the above tested code in your browser you would get the following output:

1
2
3
4
5
6
7
8
9
10

That's what I was looking for! okay, so that's how it's done. I hope this helps someone else besides me.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *