Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

extract()

Synopsis

    int extract ( array arr [, int options [, string prefix]] )

The extract() function converts elements in an array into variables in their own right, an act commonly called "exporting" in other languages. Extract takes a minimum of one parameter, an array, and returns the number of elements extracted. This is best explained using code:

    $Wales = "Swansea";
    $capitalcities = array("England"=>"London",
      "Scotland"=>"Edinburgh", "Wales"=>"Cardiff");
    extract($capitalcities);
    print $Wales;

After calling extract, the England, Scotland, and Wales keys become variables in their own right ($England, $Scotland, and $Wales), with their values set to London, Edinburgh, and Cardiff, respectively. By default, extract() will overwrite any existing variables, meaning that $Wales's original value of Swansea will be overwritten with Cardiff. The new variables are copies of those in the array, and not references.

This behavior can be altered using the second parameter, and averted using the third parameter. Parameter two takes a special constant value that allows you to decide how values will be treated if there is an existing variable, and parameter three allows you to prefix each extract variable with a special string. The possible values of the second parameter are shown in Table 5-6.

Table 5-6. Possible values for the second parameter to extract()

EXTR_OVERWRITE

On collision, overwrite the existing variable

EXTR_SKIP

On collision, do not overwrite the existing variable

EXTR_PREFIX_SAME ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page