The function Keyword
The keyword function
is used to declare user-defined functions in PHP. A function accepts parameters, executes code, and can return a result. Declared functions can be called multiple times in different parts of the program.
Syntax
function functionName($param1, $param2, ...) {
return $result;
}
Example
Let's create a simple function to add two numbers:
<?php
function sum($a, $b) {
return $a + $b;
}
echo sum(2, 3);
?>
Code execution result:
5
Example
A function can return different data types. Let's create a function that returns an array:
<?php
function createArray($a, $b) {
return [$a, $b];
}
print_r(createArray(1, 2));
?>
Code execution result:
[1, 2]
Example
Functions can have default parameter values:
<?php
function greet($name = 'Guest') {
return "Hello, $name!";
}
echo greet();
echo greet('John');
?>
Code execution result:
'Hello, Guest!'
'Hello, John!'
See Also
-
the
return
command,
which returns a value from a function