A function is a block of statements that can be used repeatedly in a program. Functions are only executed in a program when called.
PHP allows users to define their own functions. A user-defined function declaration starts with the keyword function
and contains all the code inside the {
… }
braces.
function functionName() {
code to be executed;
}
In the example below, we create a function named hello()
. The function outputs “Hello world!”. To call this function, write its name followed by brackets ();
.
<?phpfunction hello() { // defining the functionecho "Hello world!";}hello(); // calling the function?>
PHP functions can also have parameters passed to them. A function can have as many parameters as it wants. These parameters work like variables inside of our function.
<?phpfunction bornIn($name, $year) {echo "$name was born in $year \n";}bornIn("Kim", "1960");bornIn("Jon", "1998");bornIn("Tim", "1990");?>
A function can return a value to the script that called the function using the return
statement. The return value may be of any type (including arrays and objects).
<?phpfunction addValues($value1, $value2){$total = $value1 + $value2;return $total;}echo addValues(8, 20); // Outputs: 28?>
Free Resources