PHP: Using variable variables.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    PHP: Using variable variables.

    Using the code below you can turn array indices into variables that can be accessed as a normal variable would be.



    [code=php]
    <?php
    /**
    * @author Mark Skilbeck - MAHCUZ.COM
    * @title PHP: Variable variables.
    **/

    $array = array("Name" => "Foo", "Age" => 21);

    foreach( $array AS $Key => $Val )
    {
    $var = $Key;
    $$var = $Val;
    }

    // the array can now be accessed
    // by using:
    //
    // echo $array_key;

    echo "Name: $Name - Age: $Age";
    // prints Name: Foo - Age: 21
    ?>
    [/code]
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #2
    Just found out you can use the extract() function instead.

    My work is pointless!

    Comment

    • ronverdonk
      Recognized Expert Specialist
      • Jul 2006
      • 4259

      #3
      Originally posted by markusn00b
      Just found out you can use the extract() function instead.
      My work is pointless!
      No it is not. At leastt you showed how you can use and manipulate dynamic variable names.

      Ronald

      Comment

      • hsriat
        Recognized Expert Top Contributor
        • Jan 2008
        • 1653

        #4
        Originally posted by ronverdonk
        At least you showed how you can use and manipulate dynamic variable names.

        Ronald
        Yeah, I never knew about $$ trick.

        Thanks Mark...

        Comment

        Working...