mysellf mysellf - 4 months ago 10
PHP Question

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;
}

Answer

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];