Page 1 of 1

Arrays: how to find out current key if you auto-increment?

Posted: Mon Jun 23, 2003 10:03 am
by patrikG
The code is something like this:

Code: Select all

<?php
for($i=0;$i<10;$i++)
	{
	$blabla[]="hullahoop";
	echo "<br>key: ".key($blabla);
	}
?>
The problem is that no matter what the real current key is, both key() and current() return 0.

Posted: Mon Jun 23, 2003 10:16 am
by Wayne
Sorry untested but something like this should work!

Code: Select all

$thisKey = array_pop(array_keys($blabla));
echo $thisKey;
im guessing that echoing $i would have been to easy a solution. but im sure you have your reasons.

Posted: Mon Jun 23, 2003 10:17 am
by nielsene
Hmm I would think if you need to know the key at assignment time you should assign it yourself. I'ld do something like

Code: Select all

$count=count($blabla);
for ($i=0;$i<10;$i++)
{
  $blabla[$count++]="hullahoop";
  echo "<br>key:".($count-1);
}
With regards to key and current, they are only defined when you're using each() and its ilk.

Just using $i wouldn't work, if there were already entries in the array. Using a post-incrementing count ensures that no cell is over-written as long as you always auto-assign or use post-incrementing count. If you start assigning a sparse array you will have trouble.

Posted: Mon Jun 23, 2003 10:36 am
by Wayne
but count wont work if they have skip key values , ie.
$blabla = array(1=>1,89=>89)

will return a count of 2 but $blabla[2] will return nothing!

Posted: Mon Jun 23, 2003 10:47 am
by patrikG
Yes, the array has skip-values, but

Code: Select all

<?php
Code:

$thisKey = array_pop(array_keys($blabla));
echo $thisKey;
?>
did the job! Thanks a lot!

Posted: Mon Jun 23, 2003 10:51 am
by nielsene
Fair 'nuff. I don't like mixing sparse arrays with auto-assignment.

Be aware that if you nest the array_pop(array_keys()) method inside a loop, you're going to be looking at a O(n^2) algorithm.

If you're positive that the last inserted element is the largest and you want to start inserting above it, then combine the two approaches. Replace $count with $max, and initialize it to the last key. Change post-incremenet to pre-increment and you should be all set with an O(n) method.

Posted: Mon Jun 23, 2003 11:03 am
by patrikG
True, nielsene. I am using this to move array-elements up and down an array and need the absolute array-position of an element in a auto-incremented array. :)