title: PHP get index of last inserted item in array
body: <p>It's as easy as the title sounds; I need to get the index/key of the last inserted item. Why is this difficult? See the following two code samples:</p>
  
  <pre><code>$a=array();
  echo 'res='.($a[]='aaa').' - '.(count($a)-1).'&lt;br&gt;';
  echo 'res='.($a[]='bbb').' - '.(count($a)-1).'&lt;br&gt;';
  echo 'res='.($a[]='aaa').' - '.(count($a)-1).'&lt;br&gt;';
  die('&lt;pre&gt;'.print_r($a,true).'&lt;/pre&gt;');
  </code></pre>
  
  <p>Writes:</p>
  
  <pre><code>res=aaa - 0
  res=bbb - 1
  res=aaa - 2
  Array (
      [0] =&gt; aaa
      [1] =&gt; bbb
      [2] =&gt; aaa
  )
  </code></pre>
  
  <p>Sure, that seems to work fine, but see this:</p>
  
  <pre><code>$a=array();
  echo 'res='.($a[]='aaa').' - '.(count($a)-1).'&lt;br&gt;';
  echo 'res='.($a[2]='bbb').' - '.(count($a)-1).'&lt;br&gt;';
  echo 'res='.($a[]='aaa').' - '.(count($a)-1).'&lt;br&gt;';
  die('&lt;pre&gt;'.print_r($a,true).'&lt;/pre&gt;');
  </code></pre>
  
  <p>Writes:</p>
  
  <pre><code>res=aaa - 0
  res=bbb - 1       &lt;- wrong!
  res=aaa - 2       &lt;- wrong!
  Array (
      [0] =&gt; aaa
      [2] =&gt; bbb    &lt;- real key
      [3] =&gt; aaa    &lt;- real key
  )
  </code></pre>
  
  <p>So in short, the popular workaround <code>count($array)-1</code> is flawed.</p>