如何获取PHP for循环中的最后一次执行
我试图在基本如何获取PHP for循环中的最后一次执行,php,Php,我试图在基本PHPforloop中获得最后一次代码执行。目前,我已经能够执行n-1次,并在循环外静态编写n=n的代码。如果n=1,这个概念将失败,除非我在循环外使用if语句。有没有办法在循环中得到最后一次执行 <?php $total_time_months = 6; $time_now = date('Y-m-d H:i:s'); for ($x = 1; $x <= $total_time_months-1; $x++) { $offset = strtot
PHP
forloop
中获得最后一次代码执行。目前,我已经能够执行n-1
次,并在循环外静态编写n=n
的代码。如果n=1,这个概念将失败,除非我在循环外使用if语句。有没有办法在循环中得到最后一次执行
<?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\u time\u months
您已经在为迭代使用变量$x
。只需在循环中检查$x
的值:
if ($x === $total_time_months-1) {
// ... do something
}
首先。请不要使用x为什么$total\u time\u months-2
?因为循环以1开始,以5结束,建议使用$x===$total\u time\u months-1。对不起,您是正确的,它应该是$total\u time\u months-1
。