SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2004
    Location
    Orlando, FL
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    the extract() function

    I was re-visiting PHP's array functions today and came across the extract() function. I have seen this used in code before but never understood it's purpose, and wasn't able to understand the PHP docs on this.
    Can someone describe what this does and maybe give an example of how you've used it?
    Thanks in advance.

  2. #2
    SitePoint Zealot ssttoo's Avatar
    Join Date
    Jan 2004
    Location
    LA, California
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can create variables and assign values to them, using an existing array. Array keys become variable names and array values become variable values. Example:
    PHP Code:
    // this is our input array
    $ar = array ('name' => 'Joe''family' => 'Schmoe''age' => 28);

    extract($ar); // extract :)

    // echo the result, using the new variables
    echo "My name is " $name " " $family " and I am " $age " years old."
    This will produce:
    HTML Code:
    My name is Joe Schmoe and I am 28 years old.
    Then you have a bunch of options - to handle conflicts with existing variables with the same names, to use prefixes, etc. Here's the same example but with prefixes:
    PHP Code:
    $ar = array ('name' => 'Joe''family' => 'Schmoe''age' => 28);
    extract($arEXTR_PREFIX_ALL"joe");
    echo 
    "My name is " $joe_name " " $joe_family " and I am " $joe_age " years old."


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •