0

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.

Gensoki
  • 133
  • 1
  • 9

1 Answers1

0

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");
}
SyncroIT
  • 1,510
  • 1
  • 14
  • 26
  • Would you mind telling me what prefixing a $GLOBAL with & does? – Gensoki Jul 30 '16 at 21:56
  • Prefixing a variable with & pass the reference of the variable and not the value, so if you edit the variable where you passed the reference, you edit the referenced variable. Look here please: http://sandbox.onlinephpfunctions.com/code/4c3cb0dd2197f4aa03885f4c37bd04ce755d80eb – SyncroIT Jul 31 '16 at 00:05