-3

I'd like to get last element of an array in PHP.

I often do this:

$last = $this->array_of_stuff[count($this->array_of_stuff) - 1];

I'm not very happy with that though.

Any way to make the syntax shorter and avoid repeating code?

MightyPork
  • 18,270
  • 10
  • 79
  • 133
  • Even if it is "possible duplicate", seriously, WHY THE HATE? Is my question bad? – MightyPork Sep 05 '14 at 09:18
  • 1
    @MightyPork Not being part of the downvoters, did you try to google your exact question title before posting it ? First result is the proposed duplicate, third result is PHP doc of `end()`. Your question might fall in the "does not show any research effort" box for some voters – Clément Malet Sep 05 '14 at 09:33
  • @MightyPork: Marking something as a duplicate is not "hate". It tells you that there's already a question which has multiple answers that collectively have hundreds of upvotes, which means there's a very good chance that you'll find something to be happy with there. It also improves the site for future searchers, and makes it easy to manage for answerers, and so on, but even from your selfish point of view, it's a good thing, not an attack. – abarnert Sep 29 '14 at 07:08
  • I don't mind the marking as duplicate, but I'm indeed offended by the downvotes. I don't think this question deserves them, it is not bad. – MightyPork Sep 29 '14 at 08:56

2 Answers2

6

You can use end function for this case. See the manual

end($array)
George G
  • 7,443
  • 12
  • 45
  • 59
  • Is that safe though? I don't want to mess with stuff I don't understand, like the "internal pointer" wizardry... – MightyPork Sep 05 '14 at 08:24
  • sure safe, even it's fantastic ;))) – George G Sep 05 '14 at 08:25
  • 3
    That just mean that you don't want to use it in the middle of a `foreach` for example. Otherwise it's safe, but check the manual for better understanding – fejese Sep 05 '14 at 08:25
2

You can use end()

<?php

$a = array("a", "b", "c");

echo end($a);

https://eval.in/188679

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49