Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取PHP for循环中的最后一次执行_Php - Fatal编程技术网

如何获取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