By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,218 Members | 1,304 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,218 IT Pros & Developers. It's quick & easy.

Construct name of variable with variables

P: n/a
Hi there, this might sound strange,
but i need to construct a name of a variable:

i have these vars (and loads more):
$menu_ho = massageMe("$string_1");
$menu_do = massageMe("$string_2");
$menu_co = massageMe("$string_3");

they stand for some massaged strings, which are
displayed as a body title.
i also have a page called in the url like "site.php?pg=home"
what i want is to do is:

$constructed_var = $menu_$pg

so if the page is home i want to get $constructed_var = $menu_ho.

How can i do this? Hope it's clear for anyone...
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

phpfrizzle wrote:
Hi there, this might sound strange,
but i need to construct a name of a variable:


No, it doesn't sound strange...

You want what's known as a variable variable.

Go to http://www.php.net/ and search for "variable variable". Read that
and figure out how to implement it in your case.

If you still have problems, post what you tried and someone will
probably help you.

Ken

Jul 17 '05 #2

P: n/a
.oO(phpfrizzle)
Hi there, this might sound strange,
but i need to construct a name of a variable:

i have these vars (and loads more):
$menu_ho = massageMe("$string_1");
$menu_do = massageMe("$string_2");
$menu_co = massageMe("$string_3");

they stand for some massaged strings, which are
displayed as a body title.
i also have a page called in the url like "site.php?pg=home"
what i want is to do is:

$constructed_var = $menu_$pg

so if the page is home i want to get $constructed_var = $menu_ho.

How can i do this? Hope it's clear for anyone...


Can be done with variable variables, but it would be easier with an
array:

$string = array(
'ho' => massageMe("$string_1"),
'do' => massageMe("$string_2"),
'co' => massageMe("$string_3")
)

Then check if $_GET['pg'] is set and use its first two chars as an index
for the string array:

// get first two chars of $_GET['pg'] if possible, else use empty string
$pg = isset($_GET['pg']) ? substr($_GET['pg'], 0, 2) : '';

// check if the requested item exists in the array
if (isset($strings[$pg])) {
// do something useful with $strings[$pg];
} else {
// error handling
}

HTH
Micha
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.