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?

3

5 Answers 5

2
 $last_key = end(array_keys($array));   
 foreach ($array as $key => $item) {
    if ($key == $last_key) {
       // last item
       echo $item . 'last item';
    }
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this - perfect with a few tweaks to suit.
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;
}

Comments

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

Comments

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

Comments

0

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

Syntax : end($array)

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.