1

Let's say I have an array of strings that I use to create variable variables:

$var_arr = ["item1", "item2", "item3"];
foreach ($var_arr as $item) {
    $$item = array();
}

Then elsewhere in my code I have to recreate the variable variable based on a different data source:

$user_input = [ "prod1" => "widget", "qty1" => 3, "prod2" => "thingy", "qty2" => 1, "prod3" => "dingus", "qty3" => 7 ];
foreach ($user_input as $key => $value) {
    $a = "item" . substr($key, -1);
    array_push($$a, $value);
}

Are $$item and $$a the same variable, or do they reference different blocks of memory?

Troy D
  • 381
  • 2
  • 4
  • 17
  • 1
    `$$item` is creating `$item1`. `$$a` will overwrite `$item1` because it has the same name. I think this is the roughly the same as what you are doing https://eval.in/840949 (or https://eval.in/840950 because you are appending) – chris85 Aug 03 '17 at 04:20
  • Thanks @chris85 for the demos. It helped a lot to see a working example! – Troy D Aug 04 '17 at 22:56

1 Answers1

1

Both are the same what you need to consider here is that you are just referencing a variable through each assignment here:

<?php
    $hello ="hello in variable";
    $array_hello = ["hello","Yellow"];
    $hello_var = "hello";
    $item = $array_hello[0];
    echo $$hello_var;
    echo $$item; //result same as above result
?>

Here one thing to notice is ${$variable_name_string} is just using $variable_name_string to know the name of the variable you want so both will be accessing the same memory block because you are referencing same variable here. One more thing to notice here is the change in interpretation in PHP 7 from PHP 5

Expression $$foo['bar']['baz'] PHP 5 interpret it as ${$foo['bar']['baz']} while PHP 7 interpret it as ($$foo)['bar']['baz'] Refer PHP manual for more

Black Mamba
  • 13,632
  • 6
  • 82
  • 105