PHP: Target last item in array?

I have an array of images that represent an image gallery. I need to loop through the array, and if the array contains more than 8 images, I need to echo out an additional html element with the last iteration.

What have you tried so far? Searching for “PHP last element of array” points me to the end() function, which might help you.

https://www.php.net/manual/en/function.end.php

I technically got it to work using array_slice() multiple times, but I can’t imagine that’s very efficient, and it looks rather messy.

It just seems to me that you’d echo the first eight items, then use count() to see if there are more than eight and, if there are, use end() to echo the last one.

Pseudo code:

for loop = 0; loop < (min(8, count(arrayname)); loop++ {
  echo arrayname(loop)
  }
if count(arrayname) > 8 {
  echo end(arrayname)
  }

It’s very simple to get the count of an array without a loop.

if(count($array) > 8){ echo "an additional html element" ;}

Yes, I misread the original post. I was thinking the OP wanted to display the first eight elements, and the final one if there was one.

I guess they still need to cut the array short to only display 8 items.
That can be done with array_slice()
It probably depends on the end use case, if it’s pagnaton maybe array_chunk to get a count of pages.

I saw another thread asking about only displaying nine items from an array and that talked about using array_slice() - if it’s only the first n can you say why you’d slice the array rather than just stopping the display loop after n iterations? It seems an unnecessarily complex way to do it to me, but as plenty of people suggested the slice there must be something I’m missing that makes it better.

There is always more than one way to skin a cat.
I think using slice may be simpler, as you don’t need a counter or a check of the count to break out the loop. A simple foreach would do.

$n = 8; // Or any chosen number
foreach(array_slice($array, 0, $n) as $img){
      // Do Whatever
}
if(count($array) > $n){
   echo "an additional html element" ;
}

Maybe not much in it.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.