Reputation: 3
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
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:
Upvotes: 0
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
Reputation: 31614
You've got 3 problems.
break
, which terminates the loop$x++;
is a standalone statement. You don't need to set $x
to itTry this
session_start();
if(!isset($_SESSION['visit'])) $_SESSION['visit'] = 1;
if($_SESSION['visit'] < 5) $_SESSION['visit']++;
Upvotes: 1