aspen7
aspen7

Reputation: 11

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 $host variable

Thanks for any help!

Upvotes: 0

Views: 137

Answers (3)

ariefbayu
ariefbayu

Reputation: 21979

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).

Upvotes: 0

Ruel
Ruel

Reputation: 15780

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

Tested, working.

Upvotes: 2

Tim Fountain
Tim Fountain

Reputation: 33148

$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.

Upvotes: 1

Related Questions