Home > OS >  PHP, assigning a value to a variable by reference
PHP, assigning a value to a variable by reference

Time:12-11

a friend asked me to analyze the output of the following simple lines. I defined a variable x that has the string PHP, and a table called a which is a reference to x, so any changes to one of them will affect the other. First, I assigned the value "Mysql" to the first element of a, the value of x changed too. But in the second affectation, when the second element of the table a got the value "test", the value of the variable x didn't change, any explanation?

<?php
    $x = "PHP";

    $a[] = &$x;
    $a[0] = "MySql";
    
    echo $a[0]; // Output: MySql
    echo $x;   // Output: MySql

    $a[1] = "test";
    echo $a[1]; // Output: test
    echo $x; // Output: MySql
    // why last output is mySql and not test?
?>

CodePudding user response:

The reference to $x is never in $a[1]. It is only in $a[0] and therefore won't change when you assign 'test' to $a[1].

$a[] = &$x; is just adding &$x to the end of the array $a. $a at that point in your code is empty, so you are assigning &$x to the first index of $a ($a[0])

  •  Tags:  
  • php
  • Related