PHP
Beginner
PHP Functions - Creating and Using Functions
59 views
55 min read
Table of Contents
PHP Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs more maintainable.
Creating Basic Functions
Define a function using the function keyword:
<?php
// Simple function
function sayHello() {
echo "Hello, World!";
}
// Call the function
sayHello(); // Output: Hello, World!
// Function with parameters
function greetUser($name) {
echo "Hello, " . $name . "!";
}
greetUser("John"); // Output: Hello, John!
?>
Function Parameters
Functions can accept multiple parameters:
<?php
// Multiple parameters
function addNumbers($a, $b) {
return $a + $b;
}
$result = addNumbers(5, 3);
echo $result; // Output: 8
// Default parameter values
function greetWithTitle($name, $title = "Mr.") {
return $title . " " . $name;
}
echo greetWithTitle("Smith"); // Output: Mr. Smith
echo greetWithTitle("Johnson", "Dr."); // Output: Dr. Johnson
?>
Return Values
Functions can return values using the return statement:
<?php
// Return a value
function multiply($x, $y) {
return $x * $y;
}
$product = multiply(4, 7);
echo $product; // Output: 28
// Return multiple values (array)
function getNameParts($fullName) {
$parts = explode(" ", $fullName);
return [
"first" => $parts[0],
"last" => $parts[1] ?? ""
];
}
$name = getNameParts("John Doe");
echo $name["first"]; // Output: John
// Early return
function divide($a, $b) {
if ($b == 0) {
return "Cannot divide by zero";
}
return $a / $b;
}
?>
Variable Scope
Understanding local and global scope:
<?php
$globalVar = "I am global";
function testScope() {
$localVar = "I am local";
echo $localVar; // Works fine
// Access global variable
global $globalVar;
echo $globalVar; // Now accessible
// Alternative: use $GLOBALS
echo $GLOBALS['globalVar'];
}
testScope();
// echo $localVar; // Error: undefined variable
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: " . $count . "
";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
Pass by Reference
Modify the original variable:
<?php
// Pass by value (default)
function incrementValue($num) {
$num++;
return $num;
}
$x = 5;
$result = incrementValue($x);
echo $x; // Still 5
echo $result; // 6
// Pass by reference
function incrementReference(&$num) {
$num++;
}
$y = 5;
incrementReference($y);
echo $y; // Now 6
// Practical example: swap values
function swap(&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}
$first = "Hello";
$second = "World";
swap($first, $second);
echo $first . " " . $second; // World Hello
?>
Variable Functions
Call functions dynamically:
<?php
function add($a, $b) {
return $a + $b;
}
function subtract($a, $b) {
return $a - $b;
}
// Variable function
$operation = "add";
$result = $operation(10, 5); // Calls add(10, 5)
echo $result; // 15
// Function exists check
if (function_exists($operation)) {
$result = $operation(10, 5);
}
// Calculator example
function calculate($operation, $a, $b) {
$functions = [
"add" => "add",
"subtract" => "subtract",
"multiply" => function($x, $y) { return $x * $y; },
"divide" => function($x, $y) { return $y != 0 ? $x / $y : "Error"; }
];
if (isset($functions[$operation])) {
return $functions[$operation]($a, $b);
}
return "Invalid operation";
}
?>
Anonymous Functions (Closures)
Functions without names:
<?php
// Anonymous function
$greet = function($name) {
return "Hello, " . $name;
};
echo $greet("Alice"); // Hello, Alice
// Use with array functions
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
print_r($squared); // [1, 4, 9, 16, 25]
// Closure with use keyword
$multiplier = 3;
$multiply = function($number) use ($multiplier) {
return $number * $multiplier;
};
echo $multiply(4); // 12
?>
Arrow Functions (PHP 7.4+)
Shorter syntax for simple functions:
<?php
$numbers = [1, 2, 3, 4, 5];
// Traditional anonymous function
$doubled = array_map(function($n) { return $n * 2; }, $numbers);
// Arrow function
$doubled = array_map(fn($n) => $n * 2, $numbers);
// With external variable (automatic capture)
$factor = 3;
$tripled = array_map(fn($n) => $n * $factor, $numbers);
?>
Built-in Functions
PHP provides many useful built-in functions:
<?php
// String functions
$text = "Hello World";
echo strlen($text); // 11
echo strtoupper($text); // HELLO WORLD
echo substr($text, 0, 5); // Hello
// Array functions
$fruits = ["apple", "banana", "cherry"];
echo count($fruits); // 3
array_push($fruits, "date");
sort($fruits);
// Math functions
echo abs(-5); // 5
echo round(3.7); // 4
echo rand(1, 10); // Random number 1-10
echo max(1, 5, 3, 9, 2); // 9
// Date functions
echo date("Y-m-d H:i:s"); // Current date/time
echo time(); // Unix timestamp
?>
Function Documentation
Document your functions with comments:
<?php
/**
* Calculate the area of a rectangle
*
* @param float $length The length of the rectangle
* @param float $width The width of the rectangle
* @return float The area of the rectangle
*/
function calculateRectangleArea($length, $width) {
return $length * $width;
}
/**
* Validate email address
*
* @param string $email Email address to validate
* @return bool True if valid, false otherwise
*/
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
?>
Practical Examples
Password Generator
<?php
function generatePassword($length = 8, $includeSpecial = true) {
$lowercase = "abcdefghijklmnopqrstuvwxyz";
$uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = "0123456789";
$special = "!@#$%^&*()";
$chars = $lowercase . $uppercase . $numbers;
if ($includeSpecial) {
$chars .= $special;
}
$password = "";
for ($i = 0; $i < $length; $i++) {
$password .= $chars[rand(0, strlen($chars) - 1)];
}
return $password;
}
echo generatePassword(12, true);
?>
Temperature Converter
<?php
function celsiusToFahrenheit($celsius) {
return ($celsius * 9/5) + 32;
}
function fahrenheitToCelsius($fahrenheit) {
return ($fahrenheit - 32) * 5/9;
}
function convertTemperature($temp, $from, $to) {
$from = strtolower($from);
$to = strtolower($to);
if ($from === $to) return $temp;
if ($from === "celsius" && $to === "fahrenheit") {
return celsiusToFahrenheit($temp);
} elseif ($from === "fahrenheit" && $to === "celsius") {
return fahrenheitToCelsius($temp);
}
return "Invalid conversion";
}
echo convertTemperature(25, "celsius", "fahrenheit"); // 77
?>
Practice Exercise
Create functions for:
- A calculator with add, subtract, multiply, divide functions
- A function that checks if a number is prime
- A function that reverses a string
- A function that finds the largest number in an array
Key Takeaways
- Functions make code reusable and organized
- Use parameters to make functions flexible
- Return values to get results from functions
- Understand variable scope (local vs global)
- Document your functions for better maintainability