I've seen an example for echoing the very last element in an array, but how do I echo the last 3 to 4 items in PHP?
我已经看到了回显数组中最后一个元素的示例,但是如何回显PHP中的最后3到4个项目?
I want to echo in REVERSE order, so the screen would show item 10, item 9, item 8 in an array of 10 items. I will not know the number of items in the array.
我想以REVERSE顺序回显,因此屏幕将在10个项目的数组中显示项目10,项目9,项目8。我不知道数组中的项目数。
Here's my progress so far, but I know I'll need a loop or something. Thanks in advance.
到目前为止,这是我的进展,但我知道我需要一个循环或其他东西。提前致谢。
<?php
$comments = file_get_contents('comments.txt');
$array = explode("~",$comments);
for...
?????
echo $item;
?>
3 个解决方案
#1
You can try array_reverse
你可以尝试array_reverse
<?php
$a=[1,2,3,4,5];
$array = array_reverse($a);
for($i=0;$i<4;$i++){//4 is the number of elements you wish to print.
echo "{$array[$i]}\n";
}
#2
You can slice the first three off of the reversed array:
您可以将反转数组的前三个切片:
$result = array_slice(array_reverse($array), 0, 3);
foreach($result as $val) {
echo $val;
}
#3
I think, you can reverse your array i.e. $array
..array_reverse()
function will be useful for this.
我想,你可以反转你的数组,即$ array..array_reverse()函数对此有用。
And once you have reversed $array
...then you can run a loop on it and print the desired number of elements.
一旦你颠倒了$ array ...那么你可以在它上面运行一个循环并打印所需数量的元素。
#1
You can try array_reverse
你可以尝试array_reverse
<?php
$a=[1,2,3,4,5];
$array = array_reverse($a);
for($i=0;$i<4;$i++){//4 is the number of elements you wish to print.
echo "{$array[$i]}\n";
}
#2
You can slice the first three off of the reversed array:
您可以将反转数组的前三个切片:
$result = array_slice(array_reverse($array), 0, 3);
foreach($result as $val) {
echo $val;
}
#3
I think, you can reverse your array i.e. $array
..array_reverse()
function will be useful for this.
我想,你可以反转你的数组,即$ array..array_reverse()函数对此有用。
And once you have reversed $array
...then you can run a loop on it and print the desired number of elements.
一旦你颠倒了$ array ...那么你可以在它上面运行一个循环并打印所需数量的元素。