问题很简单。我有一个foreach循环在我的代码:
foreach($array as $element) {
//code
}
在这个循环中,当我们在第一次或最后一次迭代时,我希望做出不同的反应。
如何做到这一点?
问题很简单。我有一个foreach循环在我的代码:
foreach($array as $element) {
//code
}
在这个循环中,当我们在第一次或最后一次迭代时,我希望做出不同的反应。
如何做到这一点?
当前回答
当我遇到同样的问题时,我遇到了这条线索。我只需要得到第一个元素,然后我重新分析我的代码,直到这出现在我的脑海中。
$firstElement = true;
foreach ($reportData->result() as $row)
{
if($firstElement) { echo "first element"; $firstElement=false; }
// Other lines of codes here
}
上面的代码是伟大的和完整的,但如果你只需要第一个元素,那么你可以试试这段代码。
其他回答
当我遇到同样的问题时,我遇到了这条线索。我只需要得到第一个元素,然后我重新分析我的代码,直到这出现在我的脑海中。
$firstElement = true;
foreach ($reportData->result() as $row)
{
if($firstElement) { echo "first element"; $firstElement=false; }
// Other lines of codes here
}
上面的代码是伟大的和完整的,但如果你只需要第一个元素,那么你可以试试这段代码。
对于SQL查询生成脚本,或任何对第一个或最后一个元素执行不同操作的脚本,避免使用不必要的变量检查要快得多(几乎快两倍)。
目前公认的解决方案使用循环和循环内的检查,将使every_single_iteration,正确的(快速)方法如下:
$numItems = count($arr);
$i=0;
$firstitem=$arr[0];
$i++;
while($i<$numItems-1){
$some_item=$arr[$i];
$i++;
}
$last_item=$arr[$i];
$i++;
一个自制的基准测试显示如下:
Test1: 100000次模型morg
时间:1869.3430423737毫秒
Test2:模型运行100000次
时间:3235.6359958649毫秒
因此,很明显,支票的成本很高,当然,你添加的变量越多,情况就越糟糕;)
上面的一个更简化的版本,并假设您不使用自定义索引……
$len = count($array);
foreach ($array as $index => $item) {
if ($index == 0) {
// first
} else if ($index == $len - 1) {
// last
}
}
版本2 -因为我已经讨厌使用else除非必要。
$len = count($array);
foreach ($array as $index => $item) {
if ($index == 0) {
// first
// do something
continue;
}
if ($index == $len - 1) {
// last
// do something
continue;
}
}
使用reset($array)和end($array)
<?php
$arrays = [1,2,3,4,5];
$first = reset($arrays);
$last = end($arrays);
foreach( $arrays as $array )
{
if ( $first == $array )
{
echo "<li>{$array} first</li>";
}
else if ( $last == $array )
{
echo "<li>{$array} last</li>";
}
else
{
echo "<li>{$array}</li>";
}
}
演示repl.it
要找到第一个,可以这样做:
$first = true;
foreach ( $obj as $value )
{
if ( $first )
{
// do something
$first = false; //in order not to get into the if statement for the next loops
}
else
{
// do something else for all loops except the first
}
}