0

I'm currently experimenting a weird comportment, while iterating on a global var another global var take it's value

This code

$lang_list = array('fr_FR', 'en_US');
$GLOBALS['lang_list'] = $lang_list;
if(isset($_GET['lang']) && in_array($_GET['lang'], $lang_list)){
    $GLOBALS['lang'] = $_GET['lang'];
}else{
    $GLOBALS['lang'] = 'en_US';
}

var_dump($GLOBALS['lang']);
foreach($GLOBALS['lang_list'] as $lang){
    var_dump($GLOBALS['lang']);
}

return string(5) "en_US" string(5) "fr_FR" string(5) "en_US"

Is it expected due to something related to globals ?

EDIT: Thanks everyone for the explanation ! :)

sebe
  • 53
  • 7

3 Answers3

2

Yes, this is expected behavior. $GLOBALS['lang'] refers to $lang variable in the global scope. And there are only two scopes in PHP: global scope and local function scope (see this answer for more details).

Since foreach loop doesn't create a local function scope, the $lang variable belongs to the global scope. Thus, $lang and $GLOBALS['lang'] both refer to the same variable.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
2

$GLOBALS['lang'] refers to the same variable as $lang. From the manual page for $GLOBALS:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

So when you change $lang in the global scope, it also changes $GLOBALS['lang'] (and vice versa, if you change $GLOBALS['lang'] it also changes $lang). Hence in your foreach loop, $GLOBALS['lang'] get assigned the values from $GLOBALS['lang_list'] in turn.

Note that if you ran this code in a function, you would get your expected result, as $lang in this case would be defined in the function scope, not the global scope:

function test() {
    foreach($GLOBALS['lang_list'] as $lang){
        var_dump($GLOBALS['lang']);
    }
}

test();

Output:

string(5) "en_US"
string(5) "en_US"

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
0

please read https://www.php.net/manual/en/reserved.variables.globals.php manual. You refer to the same value in the code above.

Damiano93
  • 19
  • 6