look at this:
<?php
$array = array('a' => '…', 'b' => '…', 'c' => '…', 'd' => '…', 'e' => '…', 'f' => '…');
foreach ($array as $key => $val){
echo "current key: $key, next key: ".key(($array))."<br>";
}
?>
OUTPUT:
current key: a, next key: b
current key: b, next key: c
current key: c, next key: d
current key: d, next key: e
current key: e, next key: f
current key: f, next key: a
I was searching for a function to get the next key of an associative array within a foreach-loop. i tried a bit and suddenly it worked. (as you can see in my example).
BUT WHY DOES THIS WORK? Does it make sense? … not to me!
Can you explain this to me?
It’s because of the key(($array)) part but why? i mean.. it was a mistake.. i wanted to write key($array) but I forgot to delete the 2 wrapping brackets.
So it was coincidence !!!
Why does it behave this way? i mean, it’s good but … ????
According to the PHP Manual for key, key() returns the index element of the current array position.
The problem isn’t so much with
key, or even with the double parentheses. Key receives the array by reference, so the double parentheses aren’t doing much.The behavior comes from foreach. When
foreachiterates through the array, different versions of PHP will behave different on setting the array’s internalcurrentpointer, which is whatkey(),next(),current(), etc, are looking at when they are called.Arrays in PHP aren’t like arrays in most languages; they are really objects (especially associative arrays). Think of them kinda like linked lists (they are not linked lists, but just go with me for illustration purposes) – when you iterate through, you need to know where you are currently at and where you are going to be next.
What is apparently happening here is that on whatever version of PHP you are running,
foreachis setting the internalcurrentpointer to thenextelement at the beginning of the for loop, immediately after setting the$keyand$valuevariables in your code.I would definitely not depend on this behavior, as subsequent updates to PHP may break this code. It’s just a fun coincidence of this specific version. If you want the next key, look at replacing your
foreachloop. The PHP manual on next() has good examples, and be sure to also check outprev(),each(), and the other functions in the "see also" section.