开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜