简体   繁体   中英

$array variable isn't equal to $GLOBALS['players'][$name] when defined as $GLOBALS['players'][$name] = array()

Using the code below it doesn't work but when I use

<?php
    $GLOBALS['players'] = array();

    function add($name) {
        $array = $GLOBALS['players'][$name] = array();
        array_push($array, "b");
    }

    add("a");
    print_r($players);
?>

(outputs: Array ( [a] => Array ( ) )) the code here

<?php
    $GLOBALS['players'] = array();

    function add($name) {
        $array = $GLOBALS['players'][$name] = array();
        array_push($GLOBALS['players'][$name], "b");
    }

    add("a");
    print_r($players);
?>

(outputs: Array ( [a] => Array ( [0] => b ) )) it works fine. Why does $array not work when it is referencing the same array.

It's very simple, when you pass the values to $array you're passing the $GLOBAL array to a new variable, you're not referencing the variable $GLOBAL variable.

In a few words: $array and $GLOBAL are two differents variables. Doing this is like doing:

$a = 10;
$b = $a;
$b++;
print_r($a); // Will not print 11, but 10, because you edited the var $b, that is different from $a.

To solve this little trouble you must pass the variable to $array by referencing it like here:

function add($name) {
    $GLOBALS['players'][$name] = array();
    $array = &$GLOBALS['players'][$name];
    array_push($array, "b");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM