...

View Full Version : Find position (index value) of array key



mtd
07-12-2005, 04:12 AM
Hello. I need to find the position (or, index value) of various keys in an array. They are numerical, but because of an earlier asort(), they are no longer in numerical order.

In simplified form, I have:


$arrayName = array('Book','Apple','Zebra','Lake');
)
asort($arrayName)
foreach($arrayName as $key=>$value) {
echo $value.'<br>';
}
FYI - I needed to use foreach() instead of a for($i=0 ...) loop because that would mess up the order created by the asort().

Now, I must find the position of the $key in the array. Like I said, because of the asort(), a $key with the value of 0 won't necessarily be in the 0th position, etc. Is there any built in function to do this? If not, how can I find it myself?

Thanks!

mtd
07-12-2005, 05:09 AM
Never mind, I found an alternative way:

$arrayName = array('Book','Apple','Zebra','Lake');
)
asort($arrayName)
foreach($arrayName as $value) {
static $i = 0;
echo $value.'<br>';
$i++;
}

Seems I was making things much more difficult than they needed to be. I can just loop through inside the foreach(), and remove the $key value altogether. This way, $i always corresponds to the index of the current key/value.

It would be interesting to find out, though: can one find the position of a key or value in an array? I have not seen a preset php function to do this (although, I am horrible with memorizing/remembering those built in functions...)

Kurashu
07-12-2005, 05:27 AM
foreach($arrayName as $key=>$value)

?

mtd
07-12-2005, 05:40 AM
yes, that gives the values of $key and $value, but not their index position in the array - keep in mind we have used asort(), so the keys stayed with their values. Which means the $key/$value for 'Apple' would have returned 1/Apple, but after the asort(), its actual index position is 0, because it was moved to the front. If I were using sort(), which it turns out I very well probably could have, $key would also be the index position. But what if it was an associative array? the $key may not be a number at all. Unless I am understanding something incorrectly?

This is just out of interest now, I solved my problem :-)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum