我想通过使用 foreach 循环添加一些额外的值。
foreach($a as $b) {
echo $b; // this will print 1 to 6
}
现在我想用自定义文本编辑最后一项 并像这样打印
1
2
3
4
5
6 this is last.
我该怎么做?请帮助我是 PHP 新手。
最佳答案
你可以使用数组的end
<?php
$a = array(1,2,3,4,5,6);
foreach($a as $b) {
echo $b; // this will print 1 to 6
if($b == end($a))
echo "this is last.";
echo "<br>";
}
编辑 作为@ alexandr 评论,如果你有相同的值(value),你可以用 key 来做
<?php
$a = array(6,1,2,3,4,5,6);
end($a); // move the internal pointer to the end of the array
$last_key = key($a);
foreach($a as $key=>$b) {
echo $b; // this will print 1 to 6
if($key == $last_key)
echo "this is last.";
echo "<br>";
}
关于PHP 在最后一个 foreach 循环中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660190/