0
0
PhpHow-ToBeginner · 3 min read

How to Use compact() and extract() Functions in PHP

In PHP, compact() creates an array from given variable names, while extract() imports array keys as variables into the current symbol table. Use compact() to bundle variables into an array, and extract() to turn array keys into standalone variables.
📐

Syntax

compact() takes one or more variable names as strings and returns an associative array with those variable names as keys and their values.

extract() takes an associative array and imports its keys as variable names with corresponding values.

php
<?php
// compact syntax
array compact(string ...$var_names);

// extract syntax
int extract(array &$array, int $flags = EXTR_OVERWRITE, string $prefix = "");
?>
💻

Example

This example shows how compact() creates an array from variables, and extract() creates variables from an array.

php
<?php
$name = "Alice";
$age = 30;

// Use compact to create an array from variables
$userInfo = compact('name', 'age');
print_r($userInfo);

// Use extract to create variables from an array
$data = ['city' => 'Paris', 'country' => 'France'];
extract($data);
echo "City: $city, Country: $country";
?>
Output
Array ( [name] => Alice [age] => 30 ) City: Paris, Country: France
⚠️

Common Pitfalls

  • Using extract() carelessly can overwrite existing variables, causing bugs.
  • Always check or use flags like EXTR_PREFIX_SAME to avoid overwriting.
  • Passing variable names that don't exist to compact() results in keys with null values.
php
<?php
// Risky extract overwriting variables
$name = "Bob";
$data = ['name' => 'Eve'];
extract($data);
echo $name; // Outputs 'Eve', original 'Bob' lost

// Safer extract with prefix
$name = "Bob";
extract($data, EXTR_PREFIX_SAME, 'prefix');
echo $name; // Outputs 'Bob'
echo $prefix_name; // Outputs 'Eve'
?>
Output
Eve Bob Eve
📊

Quick Reference

FunctionPurposeKey Points
compact()Creates an array from variable namesInput: variable names as strings; Output: associative array
extract()Imports array keys as variablesCan overwrite variables; use flags to control behavior

Key Takeaways

Use compact() to bundle variables into an associative array by their names.
Use extract() to create variables from array keys, but beware of overwriting existing variables.
Use extract() flags like EXTR_PREFIX_SAME to avoid variable name conflicts.
Passing non-existing variable names to compact() results in null values in the array.
Always validate data before using extract() to maintain code safety.