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

Reply via email to