2082 2

BIT301 ยท 2082 ยท 10 marks

How are indexed arrays different from associative arrays? Write a PHP program to demonstrate the conversion between array and variables.

How are indexed arrays different from associative arrays? Write a PHP program to demonstrate the conversion between array and variables.[10]

Web Technology IIChapter 4: Arrays and Data StructuresIndexed arrays and associative arrays

Quick answer

PHP provides two built-in functions for converting between arrays and variables: Converts associative array keys into variable names; Syntax; Converts variables into an associative array.

Indexed Arrays vs Associative Arrays in PHP

Difference Between Indexed Arrays and Associative Arrays

FeatureIndexed ArrayAssociative Array
Index TypeUses numeric indices (0, 1, 2, ...)Uses named string keys
Key AssignmentKeys are assigned automaticallyKeys are assigned manually by the programmer
Access MethodElements accessed by position numberElements accessed by meaningful key name
Declaration$arr = array("a", "b", "c")$arr = array("key"=>"value")
Use CaseOrdered list of itemsStoring related data with labels
MemorySlightly more efficientSlightly more overhead due to string keys
Example Key$arr[0], $arr[1]$arr["name"], $arr["age"]

Conversion Between Array and Variables in PHP

PHP provides two built-in functions for converting between arrays and variables:

1. extract() - Array to Variables

  • Converts associative array keys into variable names
  • Syntax: extract($array)

2. compact() - Variables to Array

  • Converts variables into an associative array
  • Syntax: compact("var1", "var2", ...)

PHP Program

<?php

// ============================================
// PART 1: Indexed Array vs Associative Array
// ============================================

echo "=== Indexed Array ===\n";

// Indexed array - keys are automatically assigned (0, 1, 2...)
$fruits = array("Apple", "Banana", "Mango", "Orange");

// Accessing elements by numeric index
echo "First fruit: " . $fruits[0] . "\n";
echo "Second fruit: " . $fruits[1] . "\n";
echo "Third fruit: " . $fruits[2] . "\n";

// Loop through indexed array
echo "All fruits: ";
for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . " ";
}
echo "\n\n";

echo "=== Associative Array ===\n";

// Associative array - keys are named strings
$student = array(
    "name"    => "Ram Sharma",
    "age"     => 21,
    "college" => "Tribhuvan University",
    "program" => "BSc CSIT"
);

// Accessing elements by key name
echo "Name: "    . $student["name"]    . "\n";
echo "Age: "     . $student["age"]     . "\n";
echo "College: " . $student["college"] . "\n";
echo "Program: " . $student["program"] . "\n";
echo "\n";

// ============================================
// PART 2: Array to Variables using extract()
// ============================================

echo "=== Array to Variables using extract() ===\n";

$person = array(
    "first_name" => "Sita",
    "last_name"  => "Rai",
    "city"       => "Kathmandu",
    "phone"      => "9841000000"
);

// Before extract - variables do not exist
echo "Before extract():\n";
echo isset($first_name) ? "first_name exists\n" : "first_name does NOT exist\n";

// extract() converts array keys into variable names
// and array values become variable values
extract($person);

// After extract - variables are now created
echo "\nAfter extract():\n";
echo "First Name : $first_name\n";
echo "Last Name  : $last_name\n";
echo "City       : $city\n";
echo "Phone      : $phone\n";
echo "\n";

// ============================================
// PART 3: Variables to Array using compact()
// ============================================

echo "=== Variables to Array using compact() ===\n";

// Define individual variables
$subject  = "PHP Programming";
$semester = "Fifth";
$marks    = 85;
$grade    = "A";

// compact() takes variable names as strings
// and creates an associative array
$result = compact("subject", "semester", "marks", "grade");

// Display the resulting array
echo "Array created using compact():\n";
print_r($result);

echo "\nAccessing individual elements:\n";
echo "Subject  : " . $result["subject"]  . "\n";
echo "Semester : " . $result["semester"] . "\n";
echo "Marks    : " . $result["marks"]    . "\n";
echo "Grade    : " . $result["grade"]    . "\n";
echo "\n";

// ============================================
// PART 4: Round-trip demonstration
// ============================================

echo "=== Round-trip: Array -> Variables -> Array ===\n";

// Start with an array
$original = array(
    "country"  => "Nepal",
    "capital"  => "Kathmandu",
    "currency" => "Rupee"
);

echo "Original Array:\n";
print_r($original);

// Convert array to variables
extract($original);
echo "\nVariables after extract():\n";
echo "country  = $country\n";
echo "capital  = $capital\n";
echo "currency = $currency\n";

// Modify a variable
$currency = "Nepalese Rupee (NPR)";

// Convert variables back to array
$updated = compact("country", "capital", "currency");
echo "\nUpdated Array after compact():\n";
print_r($updated);

?>

Expected Output

=== Indexed Array ===
First fruit: Apple
Second fruit: Banana
Third fruit: Mango
All fruits: Apple Banana Mango Orange

=== Associative Array ===
Name: Ram Sharma
Age: 21
College: Tribhuvan University
Program: BSc CSIT

=== Array to Variables using extract() ===
Before extract():
first_name does NOT exist

After extract():
First Name : Sita
Last Name  : Rai
City       : Kathmandu
Phone      : 9841000000

=== Variables to Array using compact() ===
Array created using compact():
Array
(
    [subject] => PHP Programming
    [semester] => Fifth
    [marks] => 85
    [grade] => A
)

Accessing individual elements:
Subject  : PHP Programming
Semester : Fifth
Marks    : 85
Grade    : A

=== Round-trip: Array -> Variables -> Array ===
Original Array:
Array
(
    [country] => Nepal
    [capital] => Kathmandu
    [currency] => Rupee
)

Variables after extract():
country  = Nepal
capital  = Kathmandu
currency = Rupee

Updated Array after compact():
Array
(
    [country] => Nepal
    [capital] => Kathmandu
    [currency] => Nepalese Rupee (NPR)
)

Conclusion

An indexed array is keyed by integers starting at 0 and is read with a numeric subscript or a counting loop, while an associative array is keyed by meaningful strings and is read by name, which is what makes it the natural choice for record-like data. PHP moves between arrays and plain variables in both directions: extract() turns each key of an array into a variable of that name, and compact() collects named variables back into an associative array. The round-trip at the end of the program shows the pair working together, with the change made to $currency between the two calls appearing in the rebuilt array.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.