PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Can someone explain the variables $value and $key that are being produced at the end of the output by the following code. It seems like the foreach loop is creating two extra variables.
From the php.net ->The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. }
I don't think that the responses so far have answered the question. $GLOBALS is an array of all the variables available in the global scope. This includes the variables $key and $value in the foreach loop. They are $GLOBALS['key'] and $GLOBALS['value'] respectively. So, when the foreach loop has dealt with the superglobal arrays like $_POST and $_GET, and the 'ordinary variables' like $test_1, it then displays the values held in $key and $value. The value held in $value is that of the previous iteration of the foreach loop ie the value of $test_4, or 'keri'. The last $GLOBAL variable in the foreach loop is $key. This contains the value of $key in the previous iteration. The previous iteration was the one which told us that $GLOBALS['value'] = 'keri'. So $key contains the value 'value'