The extract() and compact() functions in PHP are useful for working with arrays and variables. extract() imports variables from an array, while compact() creates an array from variables.
extract() – Converts array keys into variable names.compact() – Converts variable names into array keys.extract(array) assigns array values to variables.compact("var1","var2") builds an associative array.
// Import array keys as variables
<?php
$array = array("name" => "John", "age" => 28);
extract($array);
echo $name;
echo $age;
?>
The keys name and age become variables $name and $age, allowing direct access to their values.
// Create array from existing variables
<?php
$name = "John";
$age = 28;
$array = compact("name", "age");
print_r($array);
?>
The variable names become array keys, producing a clean associative array.
Simulate PHP logic in real-time below
extract() ➜ Array → Variables
compact() ➜ Variables → Array
compact() for clarity and safety.extract() only in controlled scopes.extract() inside a function scope.