rob.m
rob.m

Reputation: 10571

How to find the last item of an array?

I have an array with three objects:

Ob1
Ob2
Ob3

I tried the following:

$args = array('child_of' => 184);
$categories = get_the_category($post->ID, $args);
$i = 0;
$len = count($categories);
foreach($categories as $cat) {
    if ($i == 0) {
        echo '<li><h2><a href="'.get_category_link($cat->cat_ID).'">'.$cat->name.', </a></h2></li>';
    } else if ($i == $len - 2) {
        echo '<li><h2><a href="'.get_category_link($cat->cat_ID).'">'.$cat->name.'</a></h2></li>';
    }
    $i++;
}

But I get

Ob1, Ob2

Basically if it is the last item I don't want the comma but I am not sure what is wrong with that code and why it is showing only two values.

If I do:

var_dump($len);

It gives me int(3)

Upvotes: 0

Views: 47

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

You only want your $i conditional logic to apply to $len - 1.

The easiest way to do this is to simply swap the conditionals around and offset it by one:

foreach($categories as $cat) {
  if ($i == $len - 1) {
    echo '<li><h2><a href="'.get_category_link($cat->cat_ID).'">'.$cat->name.'</a></h2></li>';
  } else {
    echo '<li><h2><a href="'.get_category_link($cat->cat_ID).'">'.$cat->name.', </a></h2></li>';
  }
  $i++;
}

Upvotes: 2

Related Questions