如何在 PHP for 循环中获取最后一次执行



我正在尝试在基本PHPforloop中获取最后一次代码执行。目前,我已经能够执行n-1次,并在循环外静态编写n=n代码。如果n = 1,除非我在循环外使用if-statement,否则此概念将失败。有没有办法在循环中获取最后一次执行?

<?php 
$total_time_months = 6;
$time_now = date('Y-m-d H:i:s');
for ($x = 1; $x <= $total_time_months-1; $x++) {
$offset = strtotime('+'. $x .' months');
echo $next_date = date('Y-m-d H:i:s', $offset)."<br>"; // this is the n-1 time
}
//do something statically knowing that there is suposed to be one more left
echo date('Y-m-d H:i:s', strtotime('+'. $total_time_months. ' months'))."<br>";
?>

对于这个问题,n = $total_time_months

首先。使用 for 循环时,您始终可以将其简化为"x

在循环中,您可以检查当前$x。对于最后一项,它将是循环计数器的最大值 - 1。

您已经在迭代中使用变量$x。只需检查循环内$x的值:

if ($x === $total_time_months-1) { 
// ... do something
}

最新更新