In PHP, functions are blocks of reusable code that perform a specific task. Functions allow you to break up your code into smaller, more manageable pieces, making it easier to read, write, and maintain. PHP provides a variety of built-in functions, and you can also create your own custom functions.
Here is an example of a built-in function in PHP:
$num = 10;
$sqrt = sqrt($num);
echo "The square root of $num is $sqrt";
In this example, the sqrt()
function is used to calculate the square root of the variable $num
, which has a value of 10. The result of the function call is stored in the variable $sqrt
, and the echo
statement is used to print the result to the screen.
Here is an example of a custom function in PHP:
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$num1 = 5;
$num2 = 3;
$result = add($num1, $num2);
echo "The sum of $num1 and $num2 is $result";
In this example, a custom function named add()
is defined that takes two arguments, $num1
and $num2
, and returns their sum. The function is called with the values 5
and 3
for $num1
and $num2
, respectively, and the result of the function call is stored in the variable $result
. The echo
statement is used to print the result to the screen.
You can also pass variables by reference to a function using the &
symbol:
function increment(&$num) {
$num++;
}
$num = 5;
increment($num);
echo "The value of num is now $num";
In this example, a custom function named increment()
is defined that takes a variable $num
by reference and increments its value by 1. The variable $num
is passed by reference to the function using the &
symbol, so any changes made to the variable inside the function are reflected outside the function as well. The function is called with the value 5
for $num
, and the echo
statement is used to print the updated value of $num
to the screen.
By using built-in and custom functions in PHP, you can write more efficient and organized code, and perform complex operations on your data with ease.