BIT301 ยท 2081 ยท 5 marks
How conversion between arrays and variables is done using extract() and compact() functions?
How conversion between arrays and variables is done using extract() and compact() functions? [5]
Quick answer
The extract() function converts an associative array into individual variables. Each key of the array becomes a variable name, and the corresponding value becomes the variable's value.
Conversion Between Arrays and Variables: extract() and compact()
1. extract() Function
Syntax
extract(array, extract_rules, prefix);
Example
<?php
$data = array("name" => "Ram", "age" => 21, "city" => "Kathmandu");
extract($data);
echo $name; // Output: Ram
echo $age; // Output: 21
echo $city; // Output: Kathmandu
?>
How it works:
- Key
"name"โ variable$name = "Ram" - Key
"age"โ variable$age = 21 - Key
"city"โ variable$city = "Kathmandu"
2. compact() Function
The compact() function does the opposite of extract(). It takes individual variables and converts them into an associative array. The variable names become the keys and their values become the array values.
Syntax
compact(var1, var2, ...);
Example
<?php
$name = "Sita";
$age = 22;
$city = "Pokhara";
$result = compact("name", "age", "city");
print_r($result);
?>
Output:
Array
(
[name] => Sita
[age] => 22
[city] => Pokhara
)
How it works:
- Variable
$nameโ key"name"with value"Sita" - Variable
$ageโ key"age"with value22 - Variable
$cityโ key"city"with value"Pokhara"
3. Relationship Between extract() and compact()
| Feature | extract() | compact() |
|---|---|---|
| Direction | Array โ Variables | Variables โ Array |
| Input | Associative array | Variable names (as strings) |
| Output | Individual variables | Associative array |
| Use case | Unpacking array data | Packing variables into array |
4. Combined Example
<?php
// Using compact() to create array
$roll = 101;
$subject = "PHP";
$marks = 85;
$student = compact("roll", "subject", "marks");
// $student = ["roll"=>101, "subject"=>"PHP", "marks"=>85]
// Using extract() to get variables back
extract($student);
echo $roll; // Output: 101
echo $subject; // Output: PHP
echo $marks; // Output: 85
?>
Summary: extract() and compact() are complementary PHP functions used to easily convert between associative arrays and individual variables, making data handling more flexible and convenient.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.