开发者

How do I use a variable as an index to an array in PHP?

开发者 https://www.devze.com 2023-01-19 22:36 出处:网络
I have a config file which has variables based on the domain of the page (HTTP_HOST) $c is an array. eg $c[\'example.com-user\'] is an entry in the config file.

I have a config file which has variables based on the domain of the page (HTTP_HOST)

$c is an array.

eg $c['example.com-user'] is an entry in the config file.

I need to pass the value of $c['example.com-user'] to a function building the variable name on the fly.

I have "example.com" in 开发者_如何学C$host variable

Thanks for any help!


<?php
    $c['example.com-user'] = "someval";
    $host = "example.com";
    echo $c[ $host . '-user'];
?>

Tested, working.


$c[$host.'-user']

Assuming you only ever need the config data for the current domain, might it be easier to have a config file per domain, rather than one monster array with all of them? Then you can just load up the relevant file at the start.


If, for example your domain stored in variable $host and username in variable $user. Then, all you have to do is, use this variables as array's key:

echo $c[ $host . "-" . $user];

if $host = 'inform.com' and $user = 'simple_user', the code above will translate into:

echo $c['inform.com-simple_user'];

You see, to concatenate string, you use '.' (dot).

0

精彩评论

暂无评论...
验证码 换一张
取 消