0

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

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
5

Arrays start at the index of 0.

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

Comments

2

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

$last_element = end($previousBalance2);

2 Comments

going to try echo end($previousBalance2['total']);
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'];.
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.