简体   繁体   中英

PHP add value in the last foreach loop

I want to add some extra values by using foreach loop.

foreach($a as $b) {
echo $b; // this will print 1 to 6 
}

Now I want to edit last item with custom text and print like this

1
2
3
4
5
6 this is last.

how can i do this? Please help I am new in PHP.

You can use end of array

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

EDIT as @ alexandr comment if you have same value you can do it with 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>";
}

You can declare inc variable, and use with array count

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

Use count, the thats way you get the size and you can use in a condicional like if

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

You can use array_slice which is a good way to slice up an array.
You can set it to get the last item(s) with negative numbers.

$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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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