This is a discussion on Construct name of variable with variables within the PHP Language forums, part of the PHP Programming Forums category; Hi there, this might sound strange, but i need to construct a name of a variable: i have these vars (...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
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... |
|
|||
|
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 |
|
|||
|
.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 |