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?

2
  • 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 eval.in/840949 (or eval.in/840950 because you are appending) Commented Aug 3, 2017 at 4:20
  • Thanks @chris85 for the demos. It helped a lot to see a working example! Commented Aug 4, 2017 at 22:56

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Between you and @chris85, I think I got it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.