faqts : Computers : Programming : Languages : PHP : Common Problems : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

31 of 37 people (84%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I convert all entries in an associative array into variables?
How can I make variables from the key names in an array?

Feb 26th, 2002 12:31
Philip Olson, Andrei Zmievski, Nathan Wallace, unknown unknown,


Use the extract() function:

  http://www.php.net/extract

  $arr = array('a' => 'apple', 'b' => 'banana');
  extract($arr);
 
  print $a; // apple
  print $b; // banana

One possible use of extract() is on fetched data from a database.  For
example:

  $result = mysql_query("SELECT foo,bar FROM tablename");

  while ($row = mysql_fetch_assoc($result)) {

    extract($row);

    print "$foo : $bar\n";
  }

Another option is to use a loop and variable variables, like so:

  $arr = array('a' => 'apple', 'b' => 'banana');

  while (list($key, $value) = each($arr)) {
    $$key = $value;
  }

  print $a; // apple
  print $b; // banana