Extracting data from Array extract() and compact() Function with Example PHP



Extracting data from Array in PHP
With the help of extract() function, we can extract data from PHP Array and compact() function is quite different from extract() function or we can say its totally opposite to extract() lets see in below lines

1. extract() function in PHP:
   In PHP  extract() is used to extract the data from the array and store into variables, As its name suggests extract obviously it is used for extracting purposes.

Syntax:
extract(array_name);

Example:
<?php
#extract() function in php
$site["cwi"]="cwipedia";
$site['pedia']="circuitcoder";
extract($site);
echo "cwi=",$cwi,"<br>";
echo "pedia=",$pedia;
?>
Output:

cwi=cwipedia
pedia=circuitcoder

2. Compact() function in PHP:
   In PHP, compact() function is used to an array or its return array with all the variables added to it
compact() function is opposite to extract() function in the PHP, compact() function creates  associative array because key value are varible name and values are varibles values

Syntax:


compact("var_name","var_name");

Example:

<?php
#compact function in PHP
$var1="cwipedia";
$var2="dot in";
$var3=compact("var1","var2");
print_r($var3);

?>

Output:

Array ( [var1] => cwipedia [var2] => dot in )

Comments