๐Ÿ“… Week 10 - Day 1: PHP Functions (Built-in & User-defined)

Monday | Duration: 3 hours

๐ŸŽฏ Learning Objectives

๐Ÿ“ฆ What are Functions?

Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs easier to maintain.

๐Ÿ”ง Built-in PHP Functions

String Functions

<?php $text = "Hello World"; // String length echo strlen($text); // 11 // Convert to uppercase echo strtoupper($text); // HELLO WORLD // Convert to lowercase echo strtolower($text); // hello world // Replace text echo str_replace("World", "PHP", $text); // Hello PHP // Substring echo substr($text, 0, 5); // Hello // Trim whitespace $name = " Ahmad "; echo trim($name); // Ahmad ?>

Array Functions

<?php $numbers = [5, 2, 8, 1, 9]; // Count elements echo count($numbers); // 5 // Sort array sort($numbers); print_r($numbers); // [1, 2, 5, 8, 9] // Add element array_push($numbers, 10); // Remove last element array_pop($numbers); // Check if value exists if (in_array(5, $numbers)) { echo "5 is in the array"; } // Get maximum value echo max($numbers); // 9 // Get minimum value echo min($numbers); // 1 ?>

Math Functions

<?php // Absolute value echo abs(-15); // 15 // Round number echo round(4.6); // 5 echo round(4.3); // 4 // Square root echo sqrt(16); // 4 // Power echo pow(2, 3); // 8 (2ยณ) // Random number echo rand(1, 100); // Random between 1 and 100 // Ceiling (round up) echo ceil(4.2); // 5 // Floor (round down) echo floor(4.8); // 4 ?>

Date & Time Functions

<?php // Current date echo date("Y-m-d"); // 2025-12-06 // Current time echo date("H:i:s"); // 14:30:45 // Full date format echo date("l, F j, Y"); // Friday, December 6, 2025 // Day of week echo date("l"); // Friday // Month name echo date("F"); // December ?>

โœ๏ธ User-Defined Functions

Basic Function

<?php // Function without parameters function greet() { echo "Hello, welcome to PHP!"; } // Call the function greet(); // Hello, welcome to PHP! ?>

Function with Parameters

<?php // Function with one parameter function greetUser($name) { echo "Hello, " . $name . "!"; } greetUser("Ahmad"); // Hello, Ahmad! greetUser("Fatima"); // Hello, Fatima! // Function with multiple parameters function addNumbers($a, $b) { echo $a + $b; } addNumbers(10, 5); // 15 ?>

Function with Return Value

<?php // Return a value function multiply($x, $y) { return $x * $y; } $result = multiply(5, 4); echo $result; // 20 // Use in expression $total = multiply(3, 7) + 10; echo $total; // 31 ?>

Function with Default Parameters

<?php function createGreeting($name, $title = "Mr.") { return $title . " " . $name; } echo createGreeting("Ahmad"); // Mr. Ahmad echo createGreeting("Fatima", "Miss"); // Miss Fatima ?>

๐ŸŽฏ Practical Function Examples

1. Calculator Functions

<?php function add($a, $b) { return $a + $b; } function subtract($a, $b) { return $a - $b; } function multiply($a, $b) { return $a * $b; } function divide($a, $b) { if ($b == 0) { return "Cannot divide by zero!"; } return $a / $b; } // Use the functions echo "10 + 5 = " . add(10, 5) . "<br>"; echo "10 - 5 = " . subtract(10, 5) . "<br>"; echo "10 ร— 5 = " . multiply(10, 5) . "<br>"; echo "10 รท 5 = " . divide(10, 5) . "<br>"; ?>

2. Validation Functions

<?php // Check if email is valid function isValidEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } // Check if password is strong function isStrongPassword($password) { return strlen($password) >= 8; } // Check if age is valid function isValidAge($age) { return $age >= 18 && $age <= 100; } // Usage if (isValidEmail("test@example.com")) { echo "Valid email"; } if (isStrongPassword("mypass123")) { echo "Strong password"; } ?>

3. Formatting Functions

<?php // Format currency function formatCurrency($amount) { return "โ‚ฆ" . number_format($amount, 2); } // Format phone number function formatPhone($phone) { return substr($phone, 0, 4) . "-" . substr($phone, 4, 3) . "-" . substr($phone, 7); } // Truncate text function truncateText($text, $length = 50) { if (strlen($text) > $length) { return substr($text, 0, $length) . "..."; } return $text; } echo formatCurrency(15000); // โ‚ฆ15,000.00 echo formatPhone("08012345678"); // 0801-234-5678 ?>

๐Ÿ”„ Variable Scope

<?php $globalVar = "I am global"; function testScope() { $localVar = "I am local"; echo $localVar; // Works // To access global variable global $globalVar; echo $globalVar; // Now works } testScope(); echo $localVar; // Error: undefined variable ?>

๐Ÿ’ป Complete Example: Grading System

<!DOCTYPE html> <html> <head> <title>Student Grading System</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; background: #f5f5f5; } .card { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 20px; } table { width: 100%; border-collapse: collapse; } th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; } th { background: #ee5a6f; color: white; } </style> </head> <body> <div class="card"> <h1>Student Grading System</h1> <?php // Function to calculate grade function calculateGrade($score) { if ($score >= 90) return "A"; elseif ($score >= 80) return "B"; elseif ($score >= 70) return "C"; elseif ($score >= 60) return "D"; else return "F"; } // Function to determine pass/fail function getStatus($score) { return $score >= 50 ? "PASS" : "FAIL"; } // Function to calculate average function calculateAverage($scores) { return array_sum($scores) / count($scores); } // Function to get highest score function getHighestScore($students) { $highest = 0; foreach ($students as $student) { if ($student['score'] > $highest) { $highest = $student['score']; } } return $highest; } // Student data $students = [ ["name" => "Ahmad Garba", "score" => 85], ["name" => "Fatima Yusuf", "score" => 92], ["name" => "Ibrahim Musa", "score" => 78], ["name" => "Aisha Mohammed", "score" => 45], ["name" => "Usman Ali", "score" => 88] ]; // Display students echo "<table>"; echo "<tr><th>Student Name</th><th>Score</th><th>Grade</th><th>Status</th></tr>"; $scores = []; foreach ($students as $student) { $name = $student['name']; $score = $student['score']; $grade = calculateGrade($score); $status = getStatus($score); $scores[] = $score; echo "<tr>"; echo "<td>$name</td>"; echo "<td>$score</td>"; echo "<td>$grade</td>"; echo "<td>$status</td>"; echo "</tr>"; } echo "</table>"; // Statistics $average = calculateAverage($scores); $highest = getHighestScore($students); echo "<h3>Statistics</h3>"; echo "<p>Average Score: " . round($average, 2) . "</p>"; echo "<p>Highest Score: $highest</p>"; echo "<p>Total Students: " . count($students) . "</p>"; ?> </div> </body> </html>

โœ๏ธ Practice Exercises

  1. Create a function that calculates area of a circle
  2. Write a function that converts Celsius to Fahrenheit
  3. Build a function that checks if a number is even or odd
  4. Create a function that generates a random password
  5. Write a function that finds the largest number in an array

โœ… Today's Deliverable

โ† Previous Course Home Next: Day 2 โ†’