The return Keyword
The keyword return terminates the execution of the current function and returns the specified value. If return is called without parameters, the function returns null. In the global scope, return terminates the execution of the current script.
Syntax
return expression; // Return a value
return; // Return null
Example
Returning a value from a function:
<?php
function square($num) {
return $num * $num;
}
echo square(4);
?>
Code execution result:
16
Example
Returning an array from a function:
<?php
function createPair($a, $b) {
return [$a, $b];
}
print_r(createPair(1, 2));
?>
Code execution result:
[1, 2]
Example
Early termination of a function:
<?php
function checkAge($age) {
if ($age < 18) {
return "Access denied";
}
return "Access granted";
}
echo checkAge(20);
?>
Code execution result:
"Access granted"