PHP - Accessing array element within the same array

与世无争的帅哥 提交于 2019-12-25 18:24:06

问题


Having an array, I want to call a value giving a key within the same array!
In my following example, I have tried to call a particular value giving the key 'default' within the same array, but without success! Is it possible to do that in PHP? Here is my array:

$inc_folders = array(
         'default' => "def_folder",
         'file'     => $inc_folders['default'] . "/textfile.txt" 
    );

calling the value in $inc_folders['file'], I would want the result be the following: "def_folder/textfile.txt"; but I obtain an error!

Please, can you help me to resolve that?
Many thanks!


回答1:


You need to assign it to a variable first; like so:

$folder = "def_folder";
$inc_folders = array(
    'default' => $folder,
    'file'     => $folder . "/textfile.txt" 
);

Or alternatively, build the array in two steps:

$inc_folders = array(
    'default' => "def_folder"
);

$inc_folders['file'] = $inc_folders['default'] . "/textfile.txt";



回答2:


like this

$inc_folders = array(
    'default' => "def_folder"
);

$inc_folders['file']= $inc_folders['default'] . "/textfile.txt";



回答3:


Here is another way, just not how you are currently trying:

$inc_folders['default'] = "def_folder";
$inc_folders['file']    = $inc_folders['default'] . "/textfile.txt";


来源:https://stackoverflow.com/questions/23617139/php-accessing-array-element-within-the-same-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!