Are there any best practices for efficiently retrieving the last data record in a loop in PHP?

When iterating through a loop in PHP, if you need to efficiently retrieve the last data record, you can store the last record in a variable within the loop and then access that variable after the loop has finished executing. This will prevent unnecessary checks or operations within the loop to determine the last record.

$lastRecord = null;

foreach ($dataRecords as $record) {
    // Process each record in the loop
    $lastRecord = $record;
}

// Retrieve the last record after the loop
if ($lastRecord) {
    // Do something with the last record
    echo $lastRecord;
}