What is a Function?
Imagine you have a task that you need to perform over and over again, like calculating a user's age or greeting them by name. Instead of writing the same code every single time, you can package it into a reusable block. In programming, this block is called a function.
A function is like a recipe. You write the recipe once (define the function), and then whenever you need to cook that dish, you just follow the recipe (call the function). This follows a core programming principle called DRY (Don't Repeat Yourself).
1. Using PHP's Built-in Functions
PHP comes with more than 1000 built-in functions that are ready for you to use. Let's look at a few simple string functions:
<?php
$message = "Hello World";
// strlen() gets the length of a string
echo strlen($message); // Outputs: 11
echo "<br>";
// str_word_count() counts the number of words in a string
echo str_word_count($message); // Outputs: 2
echo "<br>";
// date() formats the local date and time
echo "Today is " . date("Y-m-d"); // Outputs something like: Today is 2025-09-28
?>
2. Creating Your Own Function
While built-in functions are useful, the real power comes from creating your own. You define a function using the function
keyword, followed by a name and curly braces {}
.
Once you define a function, the code inside it will not run until you "call" it by writing its name followed by parentheses ()
.
<?php
// 1. Define the function
function writeMessage() {
echo "This message was written by a function!";
}
// 2. Call the function to make it run
writeMessage();
?>
3. Function Arguments (Parameters)
To make functions more flexible, we can pass information into them. These pieces of information are called arguments or parameters. They act as variables inside the function.
<?php
// This function accepts one argument: $name
function greetUser($name) {
echo "Hello, " . $name . "!";
}
// Call the function and pass "Alex" as the argument
greetUser("Alex"); // Outputs: Hello, Alex!
echo "<br>";
greetUser("Maria"); // Outputs: Hello, Maria!
?>
4. Returning Values
Sometimes you don't want a function to just display something. You want it to perform a calculation and give you the result back so you can use it somewhere else. To do this, we use the return
statement.
The return
keyword immediately stops the function and sends a value back to the code that called it.
<?php
// This function takes two numbers and returns their sum
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
// Call the function and store the returned value in a variable
$result = addNumbers(5, 10);
echo "The result is: " . $result; // Outputs: The result is: 15
?>
Functions are essential for writing clean, efficient, and maintainable code. As your projects get bigger, you'll find yourself using them all the time. In our final lesson for this module, we'll look at a special type of variable that can hold multiple values: Arrays.