Lecture Notes: PHP Functions
A function is a reusable block of code that performs a specific task. Functions:
Reduce code repetition.
Improve modularity and readability.
Simplify debugging.
PHP supports:
Built-in functions (e.g., strlen()).
User-defined functions (custom logic).
User-defined functions
Defining & Calling Functions
The syntax for defining a function in PHP is as follows:
<?php
function functionName($parameter1, $parameter2, ..., $parameterN) {
// Function body: code to be executed…
return $returnValue; // Optional return statement
?>
Calling Functions:
To execute the code within a function, you need to "call" or "invoke" it by using its
name followed by parentheses (). If the function expects parameters, you provide the
corresponding values (arguments) inside the parentheses.
Example: A simple greeting function.
function greet($name) {
return "Hello, $name!";
}
echo greet("Ahmed"); // Output: Hello, Ahmed!
Parameters & Arguments
Default Parameters and Required Parameters:
<?php
function calculateArea($length, $width = 10) {
return $length * $width;
echo calculateArea(5); // Uses $width=10 → Output: 50
?>
Return Values
A function can return a value. To return a value from a function, you use
the return statement. The return statement immediately ends the execution of the
current function and returns the value.
Example:
<?php
function getUser() {
return ["name" => "Ahmed", "email" => "[email protected]"];
$user = getUser();
echo $user["name"]; // Output: Ahmed
?>
Built-in PHP Functions:
PHP comes with a vast library of built-in functions that perform a wide range of
tasks, from string manipulation (strlen(), strtoupper()) and array handling (count(),
array_push()) to date and time functions (date(), time()) and database interaction
functions. It's essential to familiarize yourself with these to avoid reinventing the
wheel.