6

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.

1
  • if (b == 6) for example. Commented Aug 13, 2017 at 12:12

5 Answers 5

10

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>";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. How can I do it with unknown number of array?
Please note, it will not work for arrays like: [6, 1, 2, 3, 4, 5,6]
@anamahmed what do you mean by unknown number of array?
Thanks brother. Its worked. I didn't understand it in first.
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>";
}

Comments

3

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

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.