It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Create simple php variables with extract() function

By zooboole

Here I will be showing you how you can make use of your arrays in an easy way.

To explain better what I am trying to show you, let's consider the following array:

<?php
    $identity = array(
                "name" => "Sam",
                "age"  => "47",
                "country" => "USA"
                );
?>

Note: This is Associative arrays.

In a normal case, if you want to access any element of the array, you will have to do like this:

<?php
    print $identity[$name]; //This will display " Sam"
?>

Now when you use the extract() function on the array like this :

<?php
    extract($identity); //var_dump(extract($identity)) == int 3
?>

From then you can directly call the KEYS of the array as variables like this:

<?php
    print $name; // displays: Sam
?>

What happened?

extract() has changed the keys of our associative array into plain variable

Advantages

This is useful for many cases like when you need a neat code or if you are having a very big array it is becoming hard to handle. It also used sometimes, in some MVC design pattern to transfer data from one page to another.

Warning Obviously, it will be better to use $identity['name'] because that is the convention, the normal use. So, sometimes, extract() can act up and corrupt your application. And PHP manual is warning us from using it in some cases like with the $_GET, $_POST or $_FILES global variables. So you have to be sure of your inputs before using this function. Also, as you may have noticed it, it works only on associative arrays

Note:(from php official manual) If you have register_globals turned on and you use extract() on $_FILES and specify EXTR_SKIP, you may be surprised at the results. Warning This is not recommended practice and is only documented here for completeness. The use of register_globals is deprecated and calling extract() on untrusted data such as $_FILES is, as noted above, a potential security risk. If you encounter this issue, it means that you are using at least two poor coding practices.

Last updated 2024-01-11 UTC