Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP, assigning a value to a variable by reference

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?
?>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading