CACS254 Scripting Language

Scripting LanguageUnit 69 min read

PHP Arrays & Functions: Types, Loops, CRUD & Validation

Unit 6 of Scripting Language covers PHP’s array types (indexed, associative, multidimensional), array functions, custom functions with variable arguments, and form validation—essential for dynamic web apps like eSewa’s user data handling or Daraz’s product catalogs.

TAKEAWAYS:

  • PHP arrays store data flexibly (indexed, associative, or mixed) and support nested structures for complex datasets like user profiles or inventory lists.
  • Functions in PHP can accept variable arguments (...$args) and return values, enabling reusable logic (e.g., sum() for dynamic calculations).
  • foreach loops simplify array traversal, while built-in functions like array_push(), array_merge(), and count() streamline operations.
  • Form validation in PHP ensures data integrity (e.g., checking email formats or name lengths) before database storage.
  • CRUD operations (Create, Read, Update, Delete) are the backbone of dynamic web apps, linking HTML forms to PHP/MySQL logic.

1. PHP Arrays: Types and Operations

PHP arrays are ordered maps—they can store multiple values in a single variable, with keys and values. Unlike lists in other languages, PHP arrays are heterogeneous (mix data types) and dynamic (size changes at runtime).

Types of Arrays

mindmap
  root((PHP Arrays))
    Indexed
      Numeric keys (0, 1, 2...)
      Example: `$fruits = ["Apple", "Banana"]`
    Associative
      Named keys (strings)
      Example: `$user = ["name" => "Rohan", "age" => 25]`
    Multidimensional
      Arrays within arrays
      Example: `$matrix = [[1, 2], [3, 4]]`
    Mixed
      Combines indexed + associative
      Example: `$mixed = ["id" => 1, 0 => "Data"]`

Key Array Functions

Function Purpose Example
count($array) Returns array length count($fruits) → 2
array_push() Adds element to end array_push($fruits, "Orange")
array_pop() Removes last element array_pop($fruits) → "Banana"
array_merge() Combines arrays array_merge([1,2], [3,4])
array_keys() Extracts all keys array_keys($user) → ["name", "age"]
array_values() Extracts all values array_values($user) → ["Rohan", 25]

Visual: Indexed vs. Associative Array

Worked Example: User Registration Data

// Associative array for user data
$user = [
    "name" => "Rohan",
    "email" => "rohan@example.com",
    "age" => 25,
    "is_active" => true
];

// Accessing values
echo $user["name"]; // Output: Rohan
echo $user["age"];  // Output: 25

// Adding a new key-value pair
$user["country"] = "Nepal";
print_r($user);

Output:

Array
(
    [name] => Rohan
    [email] => rohan@example.com
    [age] => 25
    [is_active] => 1
    [country] => Nepal
)

2. Array Traversal with Loops

PHP provides four loop types for array traversal, each with trade-offs:

Comparison Table: Loop Methods

Loop Type Use Case Example
foreach Best for reading arrays foreach($array as $value)
for When you need index control for($i=0; $i<count($array); $i++)
while Dynamic conditions while(list($key, $val) = each($array))
array_walk() Apply a function to each element array_walk($array, "process");

Visual: foreach Loop Execution

flowchart TD
    A["Start"] --> B["Initialize \$array = ['a', 'b', 'c']"]
    B --> C["foreach (\$array as \$value)"]
    C --> D["\$value = 'a'"]
    D --> E["Process \$value"]
    E --> F["\$value = 'b'"]
    F --> E
    E --> G["\$value = 'c'"]
    G --> H["End"]

Worked Example: Summing an Array

function sumArray($numbers) {
    $total = 0;
    foreach ($numbers as $num) {
        $total += $num;
    }
    return $total;
}

$scores = [85, 92, 78];
echo sumArray($scores); // Output: 255

Trace Table:

Step $numbers $num $total
1 [85, 92, 78] 85 85
2 [85, 92, 78] 92 177
3 [85, 92, 78] 78 255

3. Custom Functions in PHP

Functions encapsulate reusable logic. PHP supports:

  • Fixed arguments (e.g., function greet($name)).
  • Variable arguments (e.g., function sum(...$numbers)).
  • Return values (e.g., return $result;).

Worked Example: Dynamic Sum Function

function sum(...$numbers) {
    $total = 0;
    foreach ($numbers as $num) {
        $total += $num;
    }
    return $total;
}

echo sum(1, 2);       // Output: 3
echo sum(10, 20, 30); // Output: 60

Visual: Variable Arguments in Action

flowchart TD
    A["sum(1, 2, 3)"] --> B["...$numbers = [1, 2, 3]"]
    B --> C["foreach loop"]
    C --> D["\$total = 1 + 2 + 3 = 6"]
    D --> E["return 6"]

Key Function Concepts

Concept Description Example
Default Parameters Set default values if argument is omitted function greet($name = "Guest")
Pass by Reference Modify original variable (use &) function increment(&$x)
Anonymous Functions Functions without names (closures) $add = function($a, $b) { return $a + $b; }

4. Form Validation and CRUD Operations

Forms collect user input, which PHP validates before storing in a database (e.g., MySQL).

Step-by-Step CRUD Workflow

flowchart LR
    A["HTML Form"] --> B["User Submits Data"]
    B --> C["PHP Validates Input"]
    C --> D["Check: Name ≤ 40 chars, Valid Email"]
    D -->|"Valid"| E["Insert into MySQL"]
    D -->|"Invalid"| F["Show Error"]
    E --> G["Display Success Message"]

Worked Example: Email Validation

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

$email = $_POST["email"];
if (validateEmail($email)) {
    echo "Valid email!";
} else {
    echo "Invalid email!";
}

Visual: Email Validation Logic

flowchart TD
    A["User enters email"] --> B["filter_var(\$email, FILTER_VALIDATE_EMAIL)"]
    B -->|"True"| C["Valid"]
    B -->|"False"| D["Invalid"]

Database Integration (MySQL)

// Connect to MySQL
$conn = new mysqli("localhost", "user", "password", "database");

// Insert validated data
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
    echo "New record created!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

## In the Real World

  1. eSewa (Nepal)

    • Idea Used: Associative Arrays for user profiles (e.g., ["user_id" => 123, "balance" => 5000, "transactions" => [...]]).
    • How: Stores transaction history as a multidimensional array before processing payments.
  2. Daraz (Nepal/E-commerce)

    • Idea Used: CRUD Operations for product catalogs.
    • How: PHP validates product details (e.g., stock > 0) before updating the MySQL database.
  3. Khalti (Digital Payments)

    • Idea Used: Variable Arguments in Functions for dynamic transaction processing.
    • How: processPayment($amount, ...$fees) calculates total cost including taxes and service charges.
  4. NTC Website (Nepal)

    • Idea Used: Array Traversal for displaying service menus.
    • How: foreach($services as $service) loops through options like "Bill Payment" or "Complaint Registration."

## Exam Tip

  1. Array Questions (5 marks):

    • Always declare the array type (indexed/associative) in your answer.
    • For foreach loops, show the loop variable and array state in your trace.
    • Example: "Write a PHP script to store user data in an associative array and display it using foreach."
  2. Function Questions (5-10 marks):

    • Variable arguments (...$args) are a common exam topic—practice writing a sum() function.
    • For CRUD, describe validation steps (e.g., "Check if email is valid using filter_var") before database operations.
  3. Common Pitfalls:

    • Forgetting to sanitize user input (use htmlspecialchars() or mysqli_real_escape_string()).
    • Confusing array_push() (adds to end) with array_unshift() (adds to start).
    • Not closing database connections ($conn->close()).
  4. Past Exam Patterns:

    • 2022 TU Question: "Design a form to store user data and validate it in PHP." → Always include HTML + PHP validation + MySQL query.
    • 2021 PU Question: "Explain foreach with an example." → Show array state after each iteration.

Pro Tip: For 10-mark questions, combine:

  • Array declaration + loop + function + validation + database code.
  • Example structure:
    // 1. Array
    $users = ["name" => $_POST["name"], "email" => $_POST["email"]];
    
    // 2. Validation
    if (strlen($users["name"]) > 40) { echo "Name too long!"; exit; }
    
    // 3. Database
    $sql = "INSERT INTO users VALUES (...)";
    

Based on the TU BCA syllabus for Scripting Language (CACS254), unit 6.

Discussion

Loading…