I have this array here...

$previousBalance2 and it has 17 records in it

I put that 17 in a variable like so..

$i = count($previousBalance2);

I echoed out the $i variable and got 17

how ever when I try this echo

echo $previousBalance2[$i]['total'];

It does not echo out anything (nothing gets displayed) and yes each record has a total and it is called total how do I fix my code so it will echo out the total of the 17th record (which is also the last record) or how would I echo out the last record of an array?

Thanks, J

share|improve this question

71% accept rate
feedback

5 Answers

up vote 2 down vote accepted

In order to print the last element of an array use the following code:

$last_element = end($previousBalance2);
share|improve this answer
going to try echo end($previousBalance2['total']); – user1269625 1 hour ago
THat won't work either, since you're running end on $previousBalance2['total']. Instead, you need to shift the ['total'] outside the brackets (on some PHP versions), or something similar to $x = end($previousBalance2); echo $x['total'];. – slugonamission 1 hour ago
feedback

Remember, arrays are zero based. This means that your first element is 0 and the last, in this case, is 16, not 17. $i-1 will do it, or a more general solution is to use end.

share|improve this answer
1  
+1 for suggesting end() – Mark Baker 1 hour ago
Just to extend, it's worth noting that end() will also work for arrays with string keys (or dictionaries, to be more precise), since the array keys are totally ordered based on insertion time. – slugonamission 1 hour ago
feedback

Arrays start at the index of 0.

echo $previousBalance2[$i - 1]['total'];
share|improve this answer
feedback

echo $previousBalance2[$i-1]['total']?

share|improve this answer
feedback

Php arrays start at 0. So try this: $i-1 instead of $i in the brackets!

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.