Functions are reusable blocks of code that perform specific tasks. They help to organize your code, improve readability, and promote code reusability.
Defining a Function
To create a function, use the function
keyword followed by the function name and parentheses. The code to be executed goes inside curly braces.
function greet($name) {
echo "Hello, $name!";
}
PHPCalling a Function
To use a function, you call it by its name followed by parentheses.
greet("Alice"); // Output: Hello, Alice!
PHPFunction Arguments
Functions can accept parameters (arguments) to pass data to them.
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$result = addNumbers(5, 3);
echo $result; // Output: 8
PHPReturn Values
Functions can return values using the return
keyword.
function calculateArea($length, $width) {
$area = $length * $width;
return $area;
}
$rectangle_area = calculateArea(4, 5);
echo $rectangle_area; // Output: 20
PHPFunction Scope
Variables declared within a function are local to that function and cannot be accessed outside it.
Built-in Functions
PHP provides a vast library of built-in functions for various tasks like string manipulation, array operations, mathematical calculations, and more.
$text = "Hello, world!";
$length = strlen($text); // Get string length
echo $length; // Output: 12
PHPBy effectively using functions, you can break down complex problems into smaller, manageable units. This improves code organization, maintainability, and efficiency. In the next article, we’ll explore PHP arrays.