How can the last data record in the loop be stored as a new variable in PHP?

To store the last data record in the loop as a new variable in PHP, you can initialize a variable outside the loop and update its value with each iteration of the loop. By doing this, the variable will hold the value of the last data record after the loop has finished executing.

$lastRecord = null;

foreach ($dataRecords as $record) {
    // Process each data record
    
    $lastRecord = $record;
}

// $lastRecord now holds the value of the last data record in the loop