Imagine a complex task, like assembling a piece of furniture. You wouldn’t want to re-read the entire instruction manual every time you need to screw a bolt. Instead, you’d use a specialized tool—like a screwdriver.
A Function in PHP is exactly like that tool: a reusable block of code that performs a specific, defined task. They make your code easier to read, debug, and reuse.
The Two Types of Functions
- Built-in Functions: Functions that are part of the core PHP language (e.g.,
echo,strlen,date). - User-Defined Functions: Functions you create yourself to handle custom tasks in your application.
1. Creating User-Defined Functions
Defining your own function is a simple three-step process:
- Start with the keyword
function. - Give the function a unique and meaningful name (following the same rules as variables).
- Add parentheses
()(which can hold parameters) and curly braces{}(which contain the code to be executed).
| Syntax | Description |
function functionName() { code to execute; } | This defines the function block. |
Example: A Simple Greeting Tool
This function simply prints a message whenever it’s called.
PHP
<?php
function displayWelcomeMessage() {
echo "<h3>Welcome to the PHP Tutorial Series!</h3>";
}
// To run the code inside the function, you must "call" it:
displayWelcomeMessage();
// Output: Welcome to the PHP Tutorial Series!
?>
2. Function Arguments (The Input)
Most tools need input to work. For example, a calculator needs numbers. In a function, the input values are called arguments (or parameters).
You list arguments inside the parentheses when defining the function.
Example: A Power Calculator
This function takes two numbers, multiplies them, and outputs the result.
PHP
<?php
// $base and $multiplier are the arguments/parameters
function calculatePower($base, $multiplier) {
$result = $base * $multiplier;
echo "The final product is: " . $result . "<br>";
}
// Calling the function and passing actual values (12 and 6)
calculatePower(12, 6); // Output: The final product is: 72
calculatePower(50, 2); // Output: The final product is: 100
?>
3. Default Argument Values
Sometimes, you want an input to be optional. You can set a default value for an argument in the function definition. If the user doesn’t pass a value, the default is used.
Example: Default Currency
PHP
<?php
function displayPrice($amount, $currency = "USD") {
echo "Total price: " . $currency . " " . $amount . "<br>";
}
displayPrice(49.99, "EUR"); // Output: Total price: EUR 49.99
displayPrice(9.99); // Output: Total price: USD 9.99 (Uses default)
?>
4. Returning Values (The Output)
So far, our functions have only used echo to print content directly. A better practice is to use the return statement.
The return statement immediately stops the function and sends the resulting value back to the code that called it. This allows you to store the result in a variable and use it later.
Example: Getting a Calculated Result
PHP
<?php
// This function doesn't echo, it returns a value.
function getShippingCost($items) {
$cost = $items * 5;
return $cost; // Return the calculated value
}
// We store the returned value in a new variable, $finalCost
$finalCost = getShippingCost(3);
echo "Your shipping fee is $" . $finalCost . ".";
// Output: Your shipping fee is $15.
?>
5. Built-in Functions in Action
You don’t always have to write your own functions. PHP provides thousands of built-in functions for common tasks, like dealing with strings or arrays.
| Function | Category | Purpose | Example |
strlen() | String | Returns the length (number of characters) of a string. | strlen("Code"); $\rightarrow$ 4 |
str_word_count() | String | Counts the number of words in a string. | str_word_count("Hello World"); $\rightarrow$ 2 |
array_push() | Array | Adds one or more elements to the end of an array. | array_push($list, "New"); |
Example of Built-in Use:
PHP
<?php
$quote = "Learning PHP is fun.";
echo "The quote has " . str_word_count($quote) . " words.";
// Output: The quote has 4 words.
?>
Next Steps
We’ve covered all the core building blocks: variables, conditions, loops, arrays, and functions. The next chapter will focus on how to securely handle data coming from a user—specifically, how to work with HTML Forms using PHP.
