我想通过使用foreach循环添加一些额外的值。
foreach($a as $b) {
echo $b; // this will print 1 to 6
}
现在我想用自定义文字编辑最后一项 并像这样打印
1
2
3
4
5
6 this is last.
我该怎么做?请帮助我是PHP的新手。
答案 0 :(得分:11)
您可以使用数组的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评论,如果你有相同的值,你可以使用键
<?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>";
}
答案 1 :(得分:3)
您可以声明inc变量,并使用数组计数
<?php
//$b is your array
$i=1;
foreach($a as $b) {
if(count($a)==$i){
echo $b; // this is last
}
$i++;
}
?>
答案 2 :(得分:3)
<?php
$a = array(1,2,3,4,5,6);
$last = count($a) - 1;
foreach($a as $k => $b) {
echo $b; // this will print 1 to 6
if($k == $last)
echo "this is last.";
echo "<br>";
}
答案 3 :(得分:2)
使用计数,这就是你获得大小的方式,你可以像在
那样使用$size=count($a);
foreach($a as $b) {
if ($b==$size)
{
echo $b. "This is the last"; // this will print 6 and text
}
else
{
echo $b; // this will print 1 to 5
}
}
答案 4 :(得分:0)
您可以使用array_slice,这是分割数组的好方法。
您可以将其设置为获取最后一个带有负数的项目。
$arr = array(1,2,3,4,5,6);
$last = array_slice($arr, -1, 1)[0]; // 6
$other = array_slice($arr, 0, -1); // [1,2,3,4,5]
foreach($other as $item){
echo $item;
}
echo $last . " this is the last";