在foreach中以PHP数组中的最后一个子项为目标

在foreach中以PHP数组中的最后一个子项为目标,php,foreach,Php,Foreach,我试图将数组的最后一个子对象(在foreach语句中)作为目标,以使我能够稍微调整此项的输出。我尝试了许多方法,但没有任何突破。我的循环非常简单: // Loop through the items foreach( $array as $item ): echo $item; endforeach; 上面的操作很好,但我想将数组中最后一项的输出更改为: // Change final item echo $item . 'last item'; 这可能吗?听起来你想要这样的东西:

我试图将数组的最后一个子对象(在foreach语句中)作为目标,以使我能够稍微调整此项的输出。我尝试了许多方法,但没有任何突破。我的循环非常简单:

// Loop through the items
foreach( $array as $item ):
    echo $item;
endforeach;
上面的操作很好,但我想将数组中最后一项的输出更改为:

// Change final item
echo $item . 'last item';

这可能吗?

听起来你想要这样的东西:

   <?php 

// PHP program to get first and 
// last iteration 

// Declare an array and initialize it 
$myarray = array( 1, 2, 3, 4, 5, 6 ); 

// Declare a counter variable and 
// initialize it with 0 
$counter = 0; 

// Loop starts from here 
foreach ($myarray as $item) { 

    if( $counter == count( $myarray ) - 1) { 

        // Print the array content 
        print( $item ); 
        print(": Last iteration"); 
    } 

    $counter = $counter + 1; 
} 

?> 

使用
count()
,这将计算数组中的所有元素。使用最后一个元素索引的计数长度。如下。在开始您的
foreach
之前,将最后一个元素设置为“最后一项”,这样您就不需要验证

$array[count($array) - 1] = $array[count($array) - 1]."Last item";
foreach( $array as $item ){
    echo $item;
}

您可以使用
end

:将数组的内部指针设置为其最后一个元素


嘿,您只需对最后一个元素使用
end
函数即可。您不需要迭代它


语法:
end($array)

echo array\u reverse($array)[0]怎么样最后一个项目“,还是您也要所有项目?可能只是重复
回显“最后一个项目”在循环之后。感谢您的帮助-经过一些调整,非常完美。
 $last_key = end(array_keys($array));   
 foreach ($array as $key => $item) {
    if ($key == $last_key) {
       // last item
       echo $item . 'last item';
    }
 }
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry