Home > Software engineering >  How to print current index or for loop in PHP?
How to print current index or for loop in PHP?

Time:09-17

The below PHP code returns 12345678910...... at a stretch.

for ($i=0; $i<1000; $i  ) {
      sleep(1);
      echo $i;
}

How can I get it to print only the current loop number instead of printing all numbers together?

CodePudding user response:

This can be easily done in php cli using the backspace character "\x08"

<?php
$length = 0;
for ($i=0; $i<1000; $i  )
{
    // delete as much character as the length of the previous number
    echo str_repeat("\x08", $length);

    sleep(1);
    echo $i;

    // get the length of the number, so you know how much you have to delete
    $length = strlen((string)$i);
}

CodePudding user response:

This is my suggested answer (applicable to browser)

a) I believe the OP wants to have the output generated to the browser interface

b) To generate the output of the count during the 1-second sleep, we need to flush the output before each sleep

c) In a browser interface, it is not possible to generate a backspace, so let's do a javascript trick to update the div

<div id=output1></div>
<?php

$index=0;

while($index < 1000) { 

    ob_start();
    echo "<script>document.getElementById('output1').innerHTML=" . $index . "</script>";

    ob_end_flush();
    @ob_flush();
    flush();    
    sleep(1);
    $index  ;
}
?>
  • Related