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