-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?

4
  • Even if it is "possible duplicate", seriously, WHY THE HATE? Is my question bad? Commented Sep 5, 2014 at 9: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 Commented Sep 5, 2014 at 9: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. Commented Sep 29, 2014 at 7: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. Commented Sep 29, 2014 at 8:56

2 Answers 2

6

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

end($array)
Sign up to request clarification or add additional context in comments.

3 Comments

Is that safe though? I don't want to mess with stuff I don't understand, like the "internal pointer" wizardry...
sure safe, even it's fantastic ;)))
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
2

You can use end()

<?php

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

echo end($a);

https://eval.in/188679

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.