0

When using [] to dynamically set array values, how do you get the last key that was filled?

For example, consider:

$array[] = 'apple';
$array[] = 'banana';
$array[] = 'orange';

How do you get the last key value (in this case 2 for "orange")?

The key() function is just returning 0 no matter which line I place it after.

ProgrammerGirl
  • 3,157
  • 7
  • 45
  • 82
  • 1
    You could use count($array) and decrease the value by 1 – asprin Oct 31 '12 at 13:02
  • @asprin: That will only work for numerically indexed arrays. – Jon Oct 31 '12 at 13:04
  • see also: http://stackoverflow.com/questions/3687358/best-way-to-get-last-element-of-an-array-w-o-deleting-it – Karoly Horvath Oct 31 '12 at 13:05
  • @Jon: that's what the OP posted... – Karoly Horvath Oct 31 '12 at 13:05
  • @KarolyHorvath: If the array includes any elements with non-numeric keys (perhaps added earlier), or if elements are later removed, counting will not work. And there is really no reason to use a "worse" version. – Jon Oct 31 '12 at 13:08
  • @Jon While that is true, I gave the OP the simplest solution. There are a number of ways in which a solution can be obtained. Also my answer was based on they array which the OP listed. And since my answer is not the ideal one, I only put it up as a comment. – asprin Oct 31 '12 at 13:11

4 Answers4

3

Please use this code:

<?php

    $array[] = 'apple';
    $array[] = 'banana';
    $array[] = 'orange';

    $count = count($array);

    $last_key = $count-1;

    $last_value = $array[$last_key];

?>
andrewsi
  • 10,807
  • 132
  • 35
  • 51
Ayman Hussein
  • 3,817
  • 7
  • 28
  • 48
0
end($array);
echo key($array);

is all you should need.

You could also use the purpose built array_search('orange',$array) if you already know the last value you entered and only need the key.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

You can get the last key with key(), but you need to call end() first:

echo key(end($array));

An alternative solution (which is less performant) is to use array_keys() and get the last element:

echo end(array_keys($array));
Jon
  • 428,835
  • 81
  • 738
  • 806
0

you can use end function

<?php
end($array);
key($array);

or just try this

echo count($array);
Shahrokhian
  • 1,100
  • 13
  • 28