Functions are blocks of code designed to perform specific tasks. Functions allow you to reuse code and improve readability in your program.
In PHP, functions are defined using the function keyword, followed by the function name and parentheses:
function functionName() {
// code to be executed;
}
This example defines a simple function that prints a greeting:
<?php
function greet() {
echo "Hello, welcome to PHP Functions!
";
}
greet();
?>
Hello, welcome to PHP Functions!
Parameters allow you to pass values to a function. This example demonstrates a function with parameters:
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
This example uses a function to add two numbers:
<?php
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
$result = addNumbers(5, 10);
echo "The sum is: $result";
?>
The sum is: 15
Functions can return values using the return keyword. The returned value can then be used in the code that called the function.
This example shows a function that returns the square of a number:
<?php
function square($number) {
return $number * $number;
}
echo "The square of 4 is: " . square(4);
?>
The square of 4 is: 16
Using functions helps keep code organized, reusable, and modular. They play a crucial role in any PHP project.