0

I am trying to target the last child of an array (within a foreach statement) to enable me to slightly adjust the output of just this item. I have tried numerous approaches but not having any breakthroughs. My loop is very simple:

// Loop through the items
foreach( $array as $item ):
    echo $item;
endforeach;

The above works fine, but I want to change the output of the final item in the array to something like:

// Change final item
echo $item . 'last item';

Is this possible?

dungey_140
  • 2,602
  • 7
  • 34
  • 68
  • What about `echo array_reverse($array)[0] . 'last item'`, or do you want all items as well? – user3783243 Jun 26 '19 at 10:45
  • 3
    Possible duplicate of [Find the last element of an array while using a foreach loop in PHP](https://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php) – user3783243 Jun 26 '19 at 10:47
  • Just `echo 'last item';` after the loop. – Nigel Ren Jun 26 '19 at 10:55

5 Answers5

2
 $last_key = end(array_keys($array));   
 foreach ($array as $key => $item) {
    if ($key == $last_key) {
       // last item
       echo $item . 'last item';
    }
 }
kensong
  • 227
  • 1
  • 3
0

It sounds like you want something like this:

   <?php 

// PHP program to get first and 
// last iteration 

// Declare an array and initialize it 
$myarray = array( 1, 2, 3, 4, 5, 6 ); 

// Declare a counter variable and 
// initialize it with 0 
$counter = 0; 

// Loop starts from here 
foreach ($myarray as $item) { 

    if( $counter == count( $myarray ) - 1) { 

        // Print the array content 
        print( $item ); 
        print(": Last iteration"); 
    } 

    $counter = $counter + 1; 
} 

?> 

Result Here

Salman
  • 112
  • 6
0

Use count(), this will count all elements of your array. Use the length of the count for your last element index. as below. Set the last element as "Last Item" before your start your foreach this way you wont need no validation.

$array[count($array) - 1] = $array[count($array) - 1]."Last item";
foreach( $array as $item ){
    echo $item;
}
LukeDS
  • 141
  • 8
0

You can use end

end : Set the internal pointer of an array to its last element

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

Hey you can simply use end function for the last element. You don't need to iterate it.

Syntax : end($array)

chaitanya
  • 352
  • 4
  • 14