1

I am trying to get the last entry in a foreach loop but struggling so far. My biggest problem is that once inside the foreach loop, I need to filter the array by eliminating every author who has 0 posts. This is my code so far:

$authors = get_users('orderby=nicename');


foreach ($authors as $author ) {
      if ( count_user_posts( $author->id ) >= 1 ) { IF LAST {special <li>} else {normal <li> }

Can anyone shed some light on how to get the last entry in this scenario? Thanks

user1945912
  • 597
  • 3
  • 9
  • 19
  • [Find the last element of an array while using a foreach loop in PHP](http://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php) – Walfie Jan 29 '13 at 00:31

2 Answers2

2

You should write a function to filter the array and then you can pop the last item off of it like this:

// use this section of code in PHP >= 5.3 - utilizes anonymous function
$filtered_array = array_filter($authors, function($author) {
    if(count_user_posts($author->id) >= 1) return true;
    return false;
});

// use this section of code for older versions of PHP - uses regular function
function author_filter($author) {
    if(count_user_posts($author->id) >= 1) return true;
    return false;
}
$filtered_array = array_filter($authors, 'author_filter');

// the rest is the same regardless of PHP version
$last_author = array_pop($filtered_array);

// output
foreach($filtered_array as $author) {
    // regular output
}
// then do special output for $last_author
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • I think this is the way to do it, although I haven't quite managed to make it work with your code yet! Thanks – user1945912 Jan 29 '13 at 11:02
  • @user1945912 What problem are you having? Note I just realized that I left off the `s` on `$authors` for the first parameter passed to `array_filter`. Maybe this was a problem for you. – Mike Brant Jan 29 '13 at 16:59
  • @user1945912 Note I just realized that I left off the `s` on `$authors` for the first parameter passed to `array_filter`. Maybe this was a problem for you. Also are you using PHP 5.3 or greater? If not you will not be able to use the anonymous function as a callback to `array_filter` as I have done. Instead, the callback function would need to be defined separately and then named in the `array_filter` call. See my updated answer. – Mike Brant Jan 29 '13 at 17:09
0
<?php
$numItems = count($arr);
echo "<ul>";
for($i = 0; $i < $numItems; $i++) {
    if(as_zero_post){
        //$i++;
        continue;       
    }
    $i == $numItems-1 ? "<li class='last-item'>".$arr[$i]."</li>" : "<li class='normal-item'>".$arr[$i]."</li>";

} 
echo "</ul>"

?>
e-Learner
  • 517
  • 1
  • 4
  • 15