SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: extract()

  1. #1
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello there. I've just stumbled accross something which is new for me. Slowly filling in my grand canyon of ignorance. Its the PHP function extract(). I haven't noticed anyone else using it in their code. I think it is useful where you loop through a result set of data. Here's an example.
    PHP Code:
    $result mysql_query("SELECT foo, bar FROM tableName");
    while (
    $row mysql_fetch_array($result)) {
       
    extract($row);
       echo 
    "foo: $foo   bar: $bar <br>";

    So rather than messing with $row["foo"] and $row["bar"]
    extract($row) places the array values into their own variables $foo and $bar, which I think is easier to work with when placing the variables inline into a string.

  2. #2
    JavaScript Guru (Big Ego) Arielladog's Avatar
    Join Date
    Jul 1999
    Location
    SC, USA
    Posts
    390
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    Yesterday freddydoesphp, gave me a solution to put all global variables in to the function, using the extract() function, so it is very useful:

    PHP Code:
        global $HTTP_POST_VARS;
        
    extract($HTTP_POST_VARS); 
    I just wanted the $HTTP_POST_VARS and not all the $GLOBALS, but it worked perfectly.

    aDog

    P.S>-Thanks freddy

  3. #3
    Grumpy Mole Man Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,066
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What a fantastically useful function

    I've never seen that before, but I'll definitely use it in the future. Thanks for the tip

    I looked it up in the PHP online manual and there are several other options for it, including specifying whether or not it over writes variables that have already been defined - you can also have it stick a prefix on the variable names if you want it to:

    http://www.php.net/manual/en/function.extract.php

  4. #4
    SitePoint Guru DenverDave's Avatar
    Join Date
    Feb 2001
    Location
    Denver, Colorado
    Posts
    630
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is great. I thought that there must be a better way than all the silly, repetitive $row("foo") stuff and had it on my list to write a function. Now with the extract($row), maybe I won't have to. Amazing how sometimes when we struggle with things, we find out later that others are not doing it the way we are.

    Thanks for potentially saving me hours and hours. Hope to give somethings back sometime.

    Dave


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
  •