The compact and extract functions help you easily convert variables to arrays and arrays back to variables. This makes managing data simpler.
0
0
Compact and extract functions in PHP
Introduction
When you want to group several variables into one array to pass around.
When you receive an array and want to create variables from its keys.
When working with templates and want to pass many variables at once.
When you want to simplify code that handles many related variables.
Syntax
PHP
array compact ( mixed $var_name1 [, mixed $... ] ) int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = "" ]] )
compact takes variable names as strings and returns an array with those variables and their values.
extract takes an array and creates variables from its keys with corresponding values.
Examples
This creates an array
['name' => 'Alice', 'age' => 25] from variables.PHP
$name = "Alice"; $age = 25; $data = compact('name', 'age'); print_r($data);
This creates variables
$city and $country from the array keys.PHP
$info = ['city' => 'Paris', 'country' => 'France']; extract($info); echo $city . ', ' . $country;
Sample Program
This program shows how compact groups variables into an array, and extract creates variables back from that array.
PHP
<?php // Define variables $firstName = "John"; $lastName = "Doe"; $age = 30; // Use compact to create an array from variables $userData = compact('firstName', 'lastName', 'age'); // Show the array print_r($userData); // Now extract variables back from the array extract($userData); // Use the extracted variables echo "Name: $firstName $lastName\n"; echo "Age: $age\n"; ?>
OutputSuccess
Important Notes
Be careful with extract as it can overwrite existing variables if keys match.
You can use flags with extract to control how variables are created, like adding prefixes.
Summary
compact turns variables into an array using their names.
extract turns array keys into variables with their values.
These functions help organize and reuse data easily.