如何在PHP中的for循环中使睡眠函数正确响应

I am writing a script that gets an eight digit number then reads it out loud. I want a delay of two seconds between the numbers as they are being read out. The problem is that even after setting the delay with sleep(), all my numbers are read out at once which leads to a summon-like audio that is getting me closer to being the antichrist with every debug. Here is my code. How do i get my loop to execute so that the numbers are read as e.g 2 .... 1 .... 3 .... 4 .... (where .... = 2 seconds.)

for($counter=0; $counter<count($dbId); $counter++)
{
    $fileName = array_search($dbId[$counter], $letterArray);
    echo "<audio src='../resources/audio/mp3/'.$fileName.'.mp3' autoplay></audio>";
    echo time() . "<br />";
    sleep(2);
}

You have an incorrect understanding of sleep. Sleep delays the php script, which delays the response from the server, but the resulting webpage that you serve will be exactly the same with or without sleep. It will just take longer to load. You can not control this from php you have to do it on the client somehow. Look at this question for example.

PHP is a hypertext pre processor. Meaning it's output cannot be send intermittently to the browser.

You have two options.

  1. Create all audio elements without autoplay and handle your desired functionality with javascript using setInterval
  2. Make a series of AJAX requests in order to get the next audio element enabling the autoplay feature. These requests can be fired by either listening for the audio to finish, or again using setInterval