What potential issue could arise when trying to access the previous and next elements of an array within a foreach loop?

When trying to access the previous and next elements of an array within a foreach loop, the issue arises because the foreach loop only iterates over the current element of the array and does not provide direct access to the previous or next elements. To solve this issue, you can use a for loop instead of a foreach loop, allowing you to access the previous and next elements based on the current index.

$array = [1, 2, 3, 4, 5];

for ($i = 0; $i < count($array); $i++) {
    $current = $array[$i];
    
    $previous = ($i > 0) ? $array[$i - 1] : null;
    $next = ($i < count($array) - 1) ? $array[$i + 1] : null;

    echo "Current: $current, Previous: $previous, Next: $next" . PHP_EOL;
}