Search code examples
phpphp-7.2

Why is this foreach loop iterating twice?


Question's in the title really - I have this foreach loop and it appears to be iterating over my array twice.

ob_start();

$array = str_split(strtolower($_GET['text']));

foreach ($array as $char) {
    error_log($_GET['text'] . ', ' . sizeof($array) . ', ' . $char);
}

$result = ob_get_contents(); 

I am finding the code above is producing the following log when passing in the URL like so: index.php?text=Hi

[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i

The debug shows the array to only be 2 long, so I'm really not sure what it could be. Thanks!


After more debugging, I have found the following:

if (!isset($_GET['text'])) {
    header('HTTP/1.0 404 Not Found');
    die();
}

echo uniqid() . '</br>';

//ob_start();

$total = 0;
$array = str_split(strtolower($_GET['text']));

foreach ($array as $char) {
    echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
}

//$result = ob_get_contents();

echo $result;

Produces this:

5bce311d3d6bd
Hi, 2, h
Hi, 2, i

But un-commenting the two commented out lines, gives me this:

5bce313b9f29d
Hi, 2, h
Hi, 2, i
Hi, 2, h
Hi, 2, i

Solution

  • I think I perhaps have more to learn about the ob_... functionality?

    This following code seems to be consistent and reliable:

    if (!isset($_GET['text'])) {
        header('HTTP/1.0 404 Not Found');
        die();
    }
    
    echo uniqid() . '</br>';
    
    ob_start();
    
    $total = 0;
    $array = str_split(strtolower($_GET['text']));
    
    foreach ($array as $char) {
        echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
    }
    
    ob_flush();