0

I have 2 arrays and would like to print to screen after each iteration of the nested loop.

$array1 = array('1','2','3','4','5');
$array2 = array('a','b','c','d','e');
if (ob_get_level() == 0) ob_start();
    foreach($array1 as $number){
        foreach($array2 as $letter){
            echo $number." - ".$letter."<br>";
            sleep(2);
            ob_flush();
            flush();
        }
    }

In the above code, I would expect it would print "1 - a" then wait 2 seconds, then print "1 - b", wait 2 seconds, and so on. whats happening now, is it just prints it all at the end, so i have to wait the total time to see results.

where would i use the ob_start / ob_flush functions to get it to print after each iteration inside array2? i have tried everywhere

bart2puck
  • 2,432
  • 3
  • 27
  • 53
  • How long does it take to return a response? about 50sec? (5*5*2) – Arleigh Hix Jul 20 '23 at 18:20
  • You can't do this without `javascript` because `php` doesn't work on the loaded page, it works before the loading – Lothric Jul 20 '23 at 18:20
  • @ArleighHix yes 50 seconds. – bart2puck Jul 20 '23 at 18:21
  • @Lothric i do this in single layer loops in other places – bart2puck Jul 20 '23 at 18:23
  • @bart2puck where do you echo the text to? Cmd? – Lothric Jul 20 '23 at 18:29
  • to a web server/page for testing purpose. – bart2puck Jul 20 '23 at 18:30
  • Thanks for the responses. This works perfectly fine in command line. I didn't add, but didnt think it would matter that I am working in the laravel framework. – bart2puck Jul 20 '23 at 18:36
  • Alas this subject is hopeless. With our server I googled for days and none of the solutions I found ever worked, after an upgrade tot PHP 8. It has very probably to do with your Apache/nginx configuration, so nothing you can do in PHP, flushing or ob_flushing does nothing. Had to rewrite large parts of our system. I use AJAX now for streaming output and it SUCKS and is overly complicated. Good luck. – Roemer Jul 20 '23 at 19:16

1 Answers1

0

I am guessing when you say print to screen you are talking about the server, in that case you need to move the ob_flush() and flush() outside the inner loop.

This way the output will be flushed after each iteration of $array2:

$array1 = array('1','2','3','4','5');
$array2 = array('a','b','c','d','e');

if (ob_get_level() == 0) ob_start();

foreach ($array1 as $number) {
    foreach ($array2 as $letter) {
        echo $number . " - " . $letter . "<br>";
        sleep(2);
    }
    ob_flush();
    flush();
}
chyke007
  • 1,478
  • 1
  • 8
  • 16