Search code examples
phploopsrefreshreload

Php reload 10 times and echo a number


I have my code :

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

    echo $i;
    header("Refresh:3");
    exit;
}

What I'm trying to do is to reload page 10 times (I thought for loop could help) and echo each time a number. So it's basically like:

echo "0" then refresh and echo "1" then refresh and echo "2" and so on for 10 times. What am I doing wrong?


Solution

  • You need to remember where the counter is and that requires using the SESSION to get around the stateless nature of a web page

    <?php
    session_start();
    if (! isset($_SESSION['cnt']) ) {
        $_SESSION['cnt'] = 0;
    }
    
    if ( $_SESSION['cnt'] < 10 ) {
        // show on page
        echo $_SESSION['cnt'];
    
        // increment count
        $_SESSION['cnt'] = $_SESSION['cnt'] + 1;
    
        header("Refresh:3");
        exit;
    }