Functions play an important role in any programming languages. It allows you to organize your code in smaller part.
A function can be called repeatedly in your program and can return or not return any value.
There are more than 1,000 built-in functions in PHP and you can also create your own function.
Here’s the syntax of a user defined function:
function functionName()
{
your code or statement here;
}
When you name a function, make sure that it reflects the code that you write so you will know its purpose.
Let’s create a sample that will print the Hello World! string.
<?php
function printMsg()
{
echo "Hello world!";
}
printMsg(); // call printMsg function
?>
The above code simply prints the string “Hello World!” by calling its function name called
printMsg
. This function does not return any value.
Now let’s create a function that return a value with arguments.
<?php
function calculate($number1, $number2)
{
return $number1 + $number2;
}
calculate(1, 1); // call calculate function
?>
The code above simply pass the parameter to calculate function using an argument
$number1
and
number2
, then it returns a value by adding the two variables.