Page 1 of 1
Foreach loop and $GLOBALS array
Posted: Mon Oct 11, 2010 7:40 pm
by steadythecourse
HI!
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.
Code: Select all
<?php
$test_1 = "matt";
$test_2 = "kim";
$test_3 = "jessica";
$test_4 = "keri";
foreach ($GLOBALS as $key => $value) {
echo $key . "- - -" . $value;
echo "<br />";
}
?>
Output
GLOBALS- - -Array
_POST- - -Array
_GET- - -Array
_COOKIE- - -Array
_FILES- - -Array
test_1- - -matt
test_2- - -kim
test_3- - -jessica
test_4- - -keri
value- - -keri
key- - -value
Thanks!
steadythecourse
Re: Foreach loop and $GLOBALS array
Posted: Mon Oct 11, 2010 9:28 pm
by Jonah Bron
Those are the $key => $value variables you create in your loop

Re: Foreach loop and $GLOBALS array
Posted: Tue Oct 12, 2010 4:04 pm
by DigitalMind
Code: Select all
$arr = array('one' => 1, 'two' => 2, 'three' => 3);
// is same as
$arr['one'] = 1;
$arr['two'] = 2;
$arr['three'] = 3;
// is that clear?
foreach($arr as $key => $value) {
echo $key . '- - -' . $value;
echo '<br />';
}
// output is
one- - -1
two- - -2
three- - -3
// see the point?
// $arr['one'] = 1 -- 'one' is a key, 1 is a value
Re: Foreach loop and $GLOBALS array
Posted: Sun Oct 17, 2010 2:11 pm
by jankidudel
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. }
arrays you can create just in 2 ways :
1. $arr = new array( "key1" => "value1", "key2" => "value2");
2. $arr["key1"] = "value1; $arr["key2"] = "value2";
Re: Foreach loop and $GLOBALS array
Posted: Mon Oct 18, 2010 12:44 am
by cpetercarter
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'
Re: Foreach loop and $GLOBALS array
Posted: Mon Oct 18, 2010 11:38 am
by Jonah Bron
cpetercarter wrote:This includes the variables $key and $value in the foreach loop.
That's what I said
