2081 11

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]

Web Technology IIChapter 4: Arrays and Data StructuresConversion between arrays and variables

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 value 22
  • Variable $city โ†’ key "city" with value "Pokhara"

3. Relationship Between extract() and compact()

Featureextract()compact()
DirectionArray โ†’ VariablesVariables โ†’ Array
InputAssociative arrayVariable names (as strings)
OutputIndividual variablesAssociative array
Use caseUnpacking array dataPacking 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.