如何获取 PHP 中数组的最后一项

How to get the last item of an array in PHP

从数据库中获取数据后,我想获取数组中的最后一项。

我的代码是这样的:

<?php
....

while($show=$getComments->fetch()){
//here i list all items 
//but i want to catch the
//last item to change its DIV color.

}

...
?>

您可以使用 array_pop();

<?php
$show = array_pop($getComments->fetch())
?>

您可以看到 array pop 将从数组中删除最后一项并将该值 return 赋给您的变量。 在此处查看 php 文档! https://www.php.net/manual/en/function.array-pop.php

您可以使用 PHP end() 函数。

This function is used to get the last item in the array. The information of this function is fully available on PHP official website you can see below by clicking the link

https://www.php.net/manual/en/function.end.php

语法:$variable = end($array);

这是您需要的:-

<?php

while($show = $getComments->fetch()) {
    $last_item_of_array = end($show);
    //the variable($last_item_of_array) above is the last item of the array
}

?>