开发者

PHP get index of last inserted item in array

开发者 https://www.devze.com 2023-01-08 06:56 出处:网络
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:

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:

$a=array();
echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>';
echo 'res='.($a[]='bbb').' - '.(count($a)-1).'<br>';
echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>';
die('<pre>'.print_r($a,true).'</pre>');

Writes:

res=aaa - 0
res=bbb - 1
res=aaa - 2
Array (
    [0]开发者_开发百科 => aaa
    [1] => bbb
    [2] => aaa
)

Sure, that seems to work fine, but see this:

$a=array();
echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>';
echo 'res='.($a[2]='bbb').' - '.(count($a)-1).'<br>';
echo 'res='.($a[]='aaa').' - '.(count($a)-1).'<br>';
die('<pre>'.print_r($a,true).'</pre>');

Writes:

res=aaa - 0
res=bbb - 1       <- wrong!
res=aaa - 2       <- wrong!
Array (
    [0] => aaa
    [2] => bbb    <- real key
    [3] => aaa    <- real key
)

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


Here is a linear (fastest) solution:

end($a);
$last_id=key($a);


You can use key($a) together with end($a)

$a=array();
$a[]='aaa'; foo($a);
$a[3]='bbb'; foo($a);
$a['foo']='ccc'; foo($a);
$a[]='ddd'; foo($a);

function foo(array $a) {
  end($a);
  echo 'count: ', count($a), ' last key: ', key($a), "\n";
}

prints

count: 1 last key: 0
count: 2 last key: 3
count: 3 last key: foo
count: 4 last key: 4


You can use the end() function to get the last element in an array, and array_keys() to return an array of the array-keys. Confusing. In practice, it works like this:

$key = end(array_keys($array));

Credit goes to hollsk in the comments.


If you are only working with numerical indexes for your array, the last auto-generated index will always be the biggest array key of the array.

So, for auto-generated indexes, using something like max(array_keys($a)) should work.

For example, this :

$a=array();
echo 'res='.($a[]='aaa').' - '.(max(array_keys($a))).'<br>';
echo 'res='.($a[2]='bbb').' - '.(max(array_keys($a))).'<br>';
echo 'res='.($a[]='aaa').' - '.(max(array_keys($a))).'<br>';
die('<pre>'.print_r($a,true).'</pre>');

Would get you :

res=aaa - 0
res=bbb - 2
res=aaa - 3

Array
(
    [0] => aaa
    [2] => bbb
    [3] => aaa
)


But note that this will not work for situations when you are the one specifying the index...


Bah, looks like I've found the answer by myself:

$last_id = array_pop(array_keys($a));


On arrays with numeric keys from 0 to n-1 I always use:

$key = array_push($array, $value)-1;

It doesn't get any faster or simpler I guess. If someone got something like this that works for other arrays please let me know.

0

精彩评论

暂无评论...
验证码 换一张
取 消