return
The PHP "return" Keyword: A Comprehensive Guide
In PHP, the return keyword exits a function and optionally passes a value back to the caller. This guide covers its syntax, practical examples, and key behaviors.
Syntax
Here is the basic syntax for using the return keyword:
The PHP syntax of return keyword
function myFunction() {
$value = 10;
return $value;
}In this example, we use the return keyword to pass the value of $value back from myFunction().
Examples
Let's look at some practical examples of how the return keyword can be used:
Examples of PHP return keyword
<?php
// Example 1
function addNumbers($a, $b)
{
return $a + $b;
}
$result = addNumbers(2, 3);
echo $result . PHP_EOL;
// Example 2
function isPositive($num)
{
if ($num > 0) {
return true;
} else {
return false;
}
}
if (isPositive(5)) {
echo "The number is positive";
} else {
echo "The number is negative";
}In these examples, we use the return keyword to pass values from functions and use them elsewhere in our code. This is useful for encapsulating logic and reusing results.
Beyond basic usage, return can exit a function early without a value (return;), pass multiple values via an array (return [$a, $b];), or return a reference by prefixing the variable with & in the function signature.
Benefits
Using the return keyword has several benefits, including:
- Code organization: Exiting a function cleanly and passing results back improves readability and structure.
- Reusability: Functions that return values can be reused across different parts of a project, reducing duplication.
Conclusion
The return keyword is essential for controlling function flow and passing results back to your code. Mastering it will help you write cleaner, more reusable PHP functions.
Practice
What is the function and usage of 'return' in PHP?