Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add value in the last foreach loop

Tags:

php

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.

like image 730
anam ahmed Avatar asked Aug 13 '17 12:08

anam ahmed


1 Answers

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>";
}
like image 177
B. Desai Avatar answered Sep 28 '22 10:09

B. Desai