mysellf
mysellf

Reputation: 3

Some newbie issue with counting in PHP

Please tell me, what am I doing wrong and how should I fix this.

I'm trying to make a simple counter, that will count on each visiting(the page) plus 1 and will stop when the number is 5. But this doesn't work - it return the same number each time.

$x = 1;

while($x <= 5) {
    echo "The number is: $x <br>";
    $x = $x++;
    break;
}

Upvotes: 0

Views: 42

Answers (3)

TerraPass
TerraPass

Reputation: 1602

The thing is, values of variables are not preserved between executions of the script. Each time a user visits this page, $x is going to be 1.

Your script will get executed from the very beginning each time the page is requested. It will define $x to be one, display its value (which will be 1 at this point), increment it and then stop, since you put break at the end of the while loop body. Even if you remove break all you're going to accomplish is this counter being displayed 5 times on the same page with values 1 to 5.

The question of how you should "fix" this is too broad to be answered in any detail. So here are several vague options for you too consider:

  • Store this value in a file on the server. Read it each time the script executes, increment it, store it back at the end.
  • Store this value in a database. Read it each time... (ditto)
  • Store this value in a cookie or make it a session variable. This way you will be able to count visits per user.

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

If I have understood correctly you need to use a session variable - chance are I have misunderstood though.

session_start();

$name='counter';
$max=5;

if( !isset( $_SESSION[$name] ) ) $_SESSION[$name]=0;
if( $_SESSION[$name] <= $max ) $_SESSION[$name]++;

echo 'Page visits: '.$_SESSION[$name];

Upvotes: 1

Machavity
Machavity

Reputation: 31614

You've got 3 problems.

  1. You have a break, which terminates the loop
  2. $x++; is a standalone statement. You don't need to set $x to it
  3. The counter will reset between calls. PHP doesn't know if this is your first or 40th time. So you will need to store this somewhere (i.e. a database or session) if you want to retain it

Try this

session_start();

if(!isset($_SESSION['visit'])) $_SESSION['visit'] = 1;

if($_SESSION['visit'] < 5) $_SESSION['visit']++;

Upvotes: 1

Related Questions