phparraysvariablesvariable-variables

How to convert a string in an array to variable using the array index in PHP


Let's say I have an array_1 containing a string which is a name of another array_2. And now I would like to convert the array index into a variable containing the array_2. I have the following working fine:

 $array_1 = array(       
    'ads'    => ['code' => 10000,  'item' => 19999, 'cost' => 'array_2'],
    'offers' => ['code' => 20000,  'item' => 29999, 'cost' => 'array_3'] );

 $array_2 = array(       
    'price'    => '232',
    'surcharge'=> '110'  );

 $ads_prices = $array_1['ads']['cost'];
 $ads_prices = $$ads_prices;
 
 print_r($ads_prices);

 Output:  Array( [price] => 232
                 [surcharge] => 110 )

However, is there a way to make it more succinct by something like this:

 $ads_prices = $array_1['ads'][$$'cost']; 

I could use extract() but it doesn't make the code any more succinct or more efficient.


Solution

  • You can use curly brackets to disambiguate your code. In your case you have:

    $ads_prices = $array_1['ads']['cost'];
    $ads_prices = $$ads_prices;
    

    So you think you could write:

    $ads_prices = $$array_1['ads']['cost'];
    

    But this is ambiguous, and will generate warning/errors and not the result you want. To disambiguate it do:

    $ads_prices = ${$array_1['ads']['cost']};
    

    Live demo: https://3v4l.org/E7T5G

    I think this is quite poorly documented in the PHP manual, or I missed it. The best example I could find was here: Variable variables. You can also use curly braces for variable property/method names of classes: $myObject->{$myMethod}().