user1269625
user1269625

Reputation: 3209

PHP array count into a variable

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

Upvotes: 0

Views: 181

Answers (5)

Wurzelgogerer
Wurzelgogerer

Reputation: 303

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

Upvotes: 2

jacek_podwysocki
jacek_podwysocki

Reputation: 807

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

$last_element = end($previousBalance2);

Upvotes: 2

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

Upvotes: 1

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Arrays start at the index of 0.

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

Upvotes: 5

slugonamission
slugonamission

Reputation: 9642

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.

Upvotes: 6

Related Questions