Web Technology II ยท Unit 4
Arrays and Data Structures
Exam-focused notes for Arrays and Data Structures (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.
Arrays and Data Structures in short
An array holds many values under one name. Arrays are the main data structure in PHP, and they are used for lists, records and results from databases.
What this unit covers
- Indexed arrays and associative arrays
- Array creation and manipulation
- Array slicing with array_slice function
- Array element insertion and removal with array_splice
- Conversion between arrays and variables
- Extract and compact functions
- String arrays and storage
Indexed arrays and associative arrays
2082 ยท 10 marks
How are indexed arrays different from associative arrays? Write a PHP program to demonstrate the conversion between array and variables.[10]
Show solved answerHide answer
Indexed Arrays vs Associative Arrays in PHP
Difference Between Indexed Arrays and Associative Arrays
| Feature | Indexed Array | Associative Array |
|---|---|---|
| Index Type | Uses numeric indices (0, 1, 2, ...) | Uses named string keys |
| Key Assignment | Keys are assigned automatically | Keys are assigned manually by the programmer |
| Access Method | Elements accessed by position number | Elements accessed by meaningful key name |
| Declaration | $arr = array("a", "b", "c") | $arr = array("key"=>"value") |
| Use Case | Ordered list of items | Storing related data with labels |
| Memory | Slightly more efficient | Slightly 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.
Conversion between arrays and variables
2081 ยท 5 marks
How conversion between arrays and variables is done using extract() and compact() functions? [5]
Show solved answerHide answer
Conversion Between Arrays and Variables: extract() and compact()
1. extract() Function
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.
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.
0 ยท 5 marks
How conversion between array and variables is done? [5]
Array element insertion and removal with array_splice
2080 ยท 5 marks
How can you remove and insert elements in an array? Explain by writing a PHP program using array_splice() for inserting and removing elements in an array. [5]
Extract and compact functions
2079 ยท 10 marks
How can you store string type data in an array? Write a PHP program to illustrate use of extract and compact functions for conversion between arrays and variables.[10]
Array slicing with array_slice function
2079 ยท 5 marks
Write a PHP program to extract subset of a string array using array_slice() function. [5]
Make Unit 4 stick
Practice BIT301 with flashcards & quizzes