What is the best way to store the result of a foreach loop in a variable in PHP?

When using a foreach loop in PHP, you can store the result in a variable by initializing an empty array before the loop, and then pushing each iteration's result into the array. This allows you to access the collected data outside of the loop.

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

foreach ($array as $item) {
    // Process each $item and store the result in $result
    $result = doSomething($item);
    
    // Add $result to the $data array
    $data[] = $result;
}

// $data now contains the results of the foreach loop