PHP get index of last inserted item in array -


The title is as simple as sounds; I need to get the index / key of the last item entered. Why is it difficult? See the following two code samples:

  $ a = array (); Echo 'res =' ($ A [] = 'aaa'). '-' (Count ($ A) -1). ' & Lt; Br> '; Echo 'res =' ($ a [] = 'BBB'). '-' (Count ($ A) -1). ' & Lt; Br> '; Echo 'res =' ($ A [] = 'aaa'). '-' (Count ($ A) -1). ' & Lt; Br> '; Die ('& lt; east & gt;' print_r ($ one, true) .. '& lt; / pre & gt;'); (<0) => 1] = & gt; BBB [2] = & gt; aaa)  

Of course, it works fine, but see:

  $ A = array (); Echo 'res =' ($ A [] = 'aaa'). '-' (Count ($ A) -1). ' & Lt; Br> '; Echo 'res =' ($ a [2] = 'bbb'). '-' (Count ($ A) -1). ' & Lt; Br> '; Echo 'res =' ($ A [] = 'aaa'). '-' (Count ($ A) -1). ' & Lt; Br> '; Die ('& lt; east & gt;' print_r ($ one, true) .. '& lt; / pre & gt;');  

writes:

  res = aaa - 0 res = bbb - 1 < - wrong! Res = aaa - 2 & lt; - wrong! Array ([0] = & gt; AAA [2] = & gt; BBB & lt; - Actual key [3] = & gt; AAA & lt; - Actual key)  

So in a nutshell, the popular workaround count ($ array) -1 is flawed.

Here's a ( fastest ) solution:

< Pre> end ($ a); $ Last_id = Key ($ one);

Comments