4 Arrays And Data Structures

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.

Arrays and Data Structures: notes

Indexed arrays and associative arrays

An indexed array uses numbers as keys, starting from 0. An associative array uses names (strings) as keys.

<?php
$colors = ["red", "green", "blue"];      // indexed
echo $colors[1];                          // green

$student = ["name" => "Ram", "age" => 21, "city" => "Pokhara"];  // associative
echo $student["name"];                    // Ram

A multidimensional array is an array of arrays, such as a table of records.

<?php
$class = [
    ["Ram", 80],
    ["Sita", 92],
];
echo $class[1][0];   // Sita
IndexedAssociative
Keys are numbersKeys are strings
Good for simple listsGood for records with named fields
$a[0]$a["name"]

Array creation and manipulation

Arrays are created with [] or array(). Elements are added with [] or with functions.

<?php
$a = [10, 20, 30];
$a[] = 40;               // add at end
array_push($a, 50);      // add at end
array_unshift($a, 5);    // add at start
array_pop($a);           // remove last
array_shift($a);         // remove first
echo count($a);          // number of items

Useful functions:

FunctionUse
count($a)number of elements
in_array($v, $a)test if a value exists
array_key_exists($k, $a)test if a key exists
array_merge($a, $b)join arrays
array_keys($a), array_values($a)get keys or values
sort($a), rsort($a)sort values, low to high or high to low
asort($a), ksort($a)sort by value or by key, keeping the pairs
array_reverse($a)reverse the order
array_sum($a)add all numbers
unset($a[2])remove one element

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 answer

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.

Open this answer on its own page โ†’

Conversion between arrays and variables

2081 ยท 5 marks

How conversion between arrays and variables is done using extract() and compact() functions? [5]

Show solved 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 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.

Open this answer on its own page โ†’

0 ยท 5 marks

How conversion between array and variables is done? [5]

An array is a single variable that holds many values, so a PHP script constantly moves data in both directions: unpacking the elements of an array into separate scalar variables that can be used one at a time, and gathering separate variables back into one array that can be passed to a function, ...

Open this answer on its own page โ†’

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]

arraysplice() is a built-in PHP function used to remove, replace, or insert elements in an array. It modifies the original array directly. --- Parameter Description ------ $array The input array (modified in place) $offset Starting index position $length Number of elements to remove $replacement ...

Open this answer on its own page โ†’

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]

--- In PHP, strings can be stored in arrays just like any other data type. PHP supports both indexed arrays and associative arrays for storing string data. - Each string is stored at a numeric index starting from 0. - $fruits[0] gives "Apple", $fruits[1] gives "Banana", etc. - Each string value i...

Open this answer on its own page โ†’

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]

arrayslice() is a built-in PHP function that extracts a portion (subset) of an array and returns it as a new array. Syntax: Parameter Description ------ array The input array start Starting index (0-based) length Number of elements to extract (optional) preservekeys Whether to preserve original k...

Open this answer on its own page โ†’