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

8
  • How long does it take to return a response? about 50sec? (5*5*2) Commented Jul 20, 2023 at 18:20
  • You can't do this without javascript because php doesn't work on the loaded page, it works before the loading Commented Jul 20, 2023 at 18:20
  • @ArleighHix yes 50 seconds. Commented Jul 20, 2023 at 18:21
  • @Lothric i do this in single layer loops in other places Commented Jul 20, 2023 at 18:23
  • @bart2puck where do you echo the text to? Cmd? Commented Jul 20, 2023 at 18:29

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.