What are some common methods for storing the result of a loop outside of the loop in PHP?

When we want to store the result of a loop outside of the loop in PHP, we can use an array to collect the results during each iteration of the loop. By pushing or appending the result to the array within the loop, we can then access and use the collected results outside of the loop.

// Initialize an empty array to store the results
$results = [];

// Loop through some data
foreach ($data as $item) {
    // Perform some operation
    $result = doSomething($item);
    
    // Store the result in the array
    $results[] = $result;
}

// Access and use the collected results outside of the loop
foreach ($results as $result) {
    // Do something with each result
    echo $result;
}