PHP Functions
A function is a reusable block of code that runs when you call it.
Syntax
function name() {
// code
}A function is a named block of code that you can run again and again. Define it with the function keyword and run it by writing its name followed by parentheses.
Functions help you avoid repetition and keep code organised.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Wrap the logic for sending a password-reset email in a function so it can be called from multiple controllers.
- Define a slugify() function that converts a blog post title to a URL-safe string and reuse it throughout the app.
- Extract the tax-calculation logic into a pure function to make it independently unit-testable.
More examples
Defining and calling a function
A named function groups related code; declaring a return type makes the contract explicit.
<?php
function greet(string $name): string {
return "Hello, $name!";
}
echo greet('Alice'); // Hello, Alice!Reusable slug generator
Encapsulating the slug logic in a function lets any part of the codebase produce consistent, URL-safe strings.
<?php
function slugify(string $title): string {
$title = strtolower(trim($title));
$title = preg_replace('/[^a-z0-9]+/', '-', $title);
return trim($title, '-');
}
echo slugify('Hello, World! 2024'); // hello-world-2024Pure function for tax calculation
Pure functions have no side effects and return the same output for the same input, making them easy to test.
<?php
function calculateTax(float $price, float $rate): float {
return round($price * $rate, 2);
}
$price = 49.99;
$tax = calculateTax($price, 0.08);
$total = $price + $tax;
echo number_format($total, 2); // 53.99
Discussion