We can use the function
keyword to define a function.
We name the function and take optional argument variables. The body of the function is in a block of code { }
function sumNum(int $x, int $y) {
echo $x + $y;
}
echo sumNum(1,2); // 3
Below are some rules for function names.
Often a function will take its arguments, do something, and return a value.
The return
keyword is used for this.
function greeting() {
return "Hello";
}
echo greeting() . " Anna";
// Output: Hello Anna
PHP automatically figures out a data type of the variable, depending on its value.
We can declare the type using a colon :
and data type before the curly bracket.
declare(strict_types=1);
function hi(): int {
return 1;
}
var_dump(hi()); // int(1)
We can add the question mark ?
before the data type to accept the type as null and data type.
function hi(): ?int {
return null;
}
var_dump(hi()); // NULL
We can return different data types using |
or multiple data types using the mixed
keyword.
function hi(): int|float {
return 2.2;
}
var_dump(hi()); // float(2.2)
function hello(): mixed {
return "Hey";
}
var_dump(hello()); // string(3) "Hey"
PHP variadic function accepts many arguments.
When we place the … operator before a parameter, the function will accept a variable number of arguments.
function sum(...$numbers) {
$total = 0;
foreach($numbers as $number) {
$total += $number;
}
return $total;
}
echo sum(10, 20, 30, 40, 50); // 150
We use the function_exists() function to check whether or not a function exists.
if (function_exists("array_combine")){
echo "Function exists";
} else {
echo "Function does not exist";
}
PHP has several built-in functions to perform a specific task.
Here are some examples.
echo strrev(" .dlrow olleH") . "</br>";
echo str_repeat("Ha ", 2) . "</br>";
echo strtoupper("hooray!") . "</br>";
echo strlen("intro") . "</br>";
/* Output:
Hello world.
Ha Ha
HOORAY!
5
*/
Arrow function is a cleaner syntax of an anonymous function. It is especially used in a call-back function.
Arrow function has a single expression. We can use the fn keyword to create arrow functions.
Syntax
fn(arguments) => expression;
Example
$array = [1,2,3];
$array2 = array_map(fn($num) => $num * $num, $array);
echo "<pre>";
print_r($array2);
echo "</pre>";
/*
Array
(
[0] => 1
[1] => 4
[2] => 9
)
*/