Search code examples
phparraysechovar-dump

Unable to access associative array values


I have two config files. The first, which is called configs.php contains an array with some values:

$welcomeConfigs = [
  "title" => "welcome",
  "description" => "a description"
];

The second file includes the configs.php one and use the its array to generate some other variables. The second file is called views.php.

$viewConfigs = VIEW . 'Configs';
$pathToViewConfigs = VIEW . '/configs.php';

include($pathToViewConfigs);

var_dump($$viewConfigs);

In index.php:

define("VIEW", "welcome");
include('views.php');

I need to store in the $title variable, for example, the value of the associative array, but when I try to do it nothing happens. I tried to use var_dump to check if the syntax was correct and I used en external fiddle to check if something was wrong, but nothing is actually wrong.

When type var_dump($$viewConfigs); the output is { ["title"]=> string(7) "welcome" ["description"]=> string(13) "a description" }

but when I type var_dump($$viewConfigs['title']); the output is NULL.

How can I fix this? What I am doing wrong?


Solution

  • You have to use this syntax:

    var_dump( ${$viewConfigs}['title'] );
    

    that interpret $viewConfigs as variable name. The form $$viewConfigs['title'] interpret as variable name the content od $viewConfigs['title'], that not exists.

    I hope I have been clear.

    (Edit:) See more about variable variables on PHP Official site