繁体   English   中英

PHP在最后一个foreach循环中添加值

[英]PHP add value in the last foreach loop

我想通过使用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评论,如果你有相同的价值,你可以使用密钥

<?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>";
}

您可以声明inc变量,并使用数组计数

<?php
//$b is your array
$i=1;
foreach($a as $b) {
if(count($a)==$i){
    echo $b; // this is last    
}
$i++;
}
?>
<?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>";
}

使用计数,这就是你获得大小的方式,你可以使用像if一样的condicional

$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 
     }
}

您可以使用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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM