Construct name of variable with variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • phpfrizzle

    Construct name of variable with variables

    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("$str ing_1");
    $menu_do = massageMe("$str ing_2");
    $menu_co = massageMe("$str ing_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=ho me"
    what i want is to do is:

    $constructed_va r = $menu_$pg

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

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

    #2
    Re: Construct name of variable with variables


    phpfrizzle wrote:[color=blue]
    > Hi there, this might sound strange,
    > but i need to construct a name of a variable:[/color]

    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

    Comment

    • Michael Fesser

      #3
      Re: Construct name of variable with variables

      .oO(phpfrizzle)
      [color=blue]
      >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("$str ing_1");
      > $menu_do = massageMe("$str ing_2");
      > $menu_co = massageMe("$str ing_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=ho me"
      >what i want is to do is:
      >
      > $constructed_va r = $menu_$pg
      >
      >so if the page is home i want to get $constructed_va r = $menu_ho.
      >
      >How can i do this? Hope it's clear for anyone...[/color]

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

      $string = array(
      'ho' => massageMe("$str ing_1"),
      'do' => massageMe("$str ing_2"),
      'co' => massageMe("$str ing_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

      Comment

      Working...