Re: get key of array (key function sucks?)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Sjef wrote:

> Hallo,
> I am adding a value to a session variable (an array). Then I want to place
> the key of the array in another session variable to keep it for later use
> (so I can return to the array to write data to it). The key function
> should work there, but it seems to be a bit strange.
> 
> Imagine:
> 
> $array = array();
> $array[] = "Yellow";
> $array[] = "Geen";
> $array[] = "Red";
> 
> foreach ($array as $key=>$value)
> {
>     print ("Key: " . $key . " has color " . $value . " | ");
>     print ("current key = " . key($array) . "<br/>");
> }
> 
> If you run the loop the key value returned from key is one higher than the
> key in $key, and the last key is null?
> 
> How do I get the present key without a problem??

You've already got it in $key. I think you will find that foreach advances
the internal array pointer by one each time it loops, so what you have is
key($array) looking at the next array element from the one in $key and
$value.

Nothing wrong with key(), just a misunderstanding on your part about how
foreach works :-)

In simplified terms, the first time through the foreach loop, this happens:

pointer at element 0
$key gets value 0
$value gets value Yellow
pointer moved to element 1

Then you use key(), which gives you - guess what?



Cheers
-- 
David Robley

"I'll tempt Adam tonight," she said evilly.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux