Create simple php variables with extract() function
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:
$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:
print $identity[$name]; //This will display " Sam"
Now when you use the extract() function on the array like this :
extract($identity); //var_dump(extract($identity)) == int 3
From then you can directly call the KEYS of the array as variables like this:
print $name; // displays: Sam
extract() has changed the keys of our associative array into plain variable
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.
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 registerglobals turned on
and you use extract() on $FILES and specify EXTRSKIP, you may be
surprised at the results. Warning This is not recommended practice and
is only documented here for completeness. The use of registerglobals
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.