Jump to content

count each time the function runs


majortom84
Go to solution Solved by majortom84,

Recommended Posts

Write a function Counter() that keeps track of the number of times it is called. This function should not take any parameters and return the number of times that it has been called.

Example:

echo Counter();//1

echo Counter(); //2

 

 

I think I would go like this...

 

$count = 0;

function Counter() {

  $count = $count + 1;

}

 

Is this too simple? Am I doing it wrong

Link to comment
Share on other sites

//$count = 0;

//static $counter = 0;

function Counter() {

global $counter;

$count = $count + 1;

return $count;

}

echo Counter();

echo Counter();

echo Counter();

 

got it to ... 111 with this so i hope im getting closer. I will keep at it

Link to comment
Share on other sites

Jacques1 was hoping you would reply with something like

It doesn't output anything but I do get an error message about an undefined variable

If that's half true then you don't have your environment set up to tell you about problems: find your php.ini, set

error_reporting = -1
display_errors = on
and restart your web server. Then try the script and see what you get.

 

There's no output because Counter() doesn't return anything to output. You get the undefined variable warnings because $count, while defined outside the function, is not defined inside the function. You don't get that variable for free.

The global thing is one solution but you should avoid it. I personally would have suggested the static $count thing you have now.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.