← Back to Chapters

PHP Array extract() & compact()

? PHP Array extract() & compact()

? Quick Overview

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.

? Key Concepts

  • extract() – Converts array keys into variable names.
  • compact() – Converts variable names into array keys.

? Syntax & Theory

  • extract(array) assigns array values to variables.
  • compact("var1","var2") builds an associative array.

? Example 1: Using extract()

? View Code Example
// Import array keys as variables
<?php
$array = array("name" => "John", "age" => 28);
extract($array);
echo $name;
echo $age;
?>

? Explanation

The keys name and age become variables $name and $age, allowing direct access to their values.

? Example 2: Using compact()

? View Code Example
// Create array from existing variables
<?php
$name = "John";
$age = 28;
$array = compact("name", "age");
print_r($array);
?>

? Explanation

The variable names become array keys, producing a clean associative array.

? Live Logic Playground

Simulate PHP logic in real-time below

 
 

? Interactive Concept Flow

extract() ➜ Array → Variables
compact() ➜ Variables → Array

? Use Cases

  • Handling form submissions
  • Passing data to templates
  • Dynamic configuration loading
  • Reducing repetitive array assignments

✅ Tips & Best Practices

  • Prefer compact() for clarity and safety.
  • Use extract() only in controlled scopes.
  • Always validate array keys before extraction.
  • Document extracted variables clearly.

? Try It Yourself

  • Extract user profile data into variables.
  • Create an array from multiple config variables.
  • Test extract() inside a function scope.