Functions in PHP can return values using the return
statement. This allows functions to process data and send back a result, making them more useful and flexible.
🔹 Why Use Return Values?
- Reusability – The function can be used multiple times without modifying the code.
- Flexibility – Functions can process and return different results based on input.
- Better Code Structure – Separates logic from output for cleaner code.
📝 Example 1: Returning a Value from a Function
This function calculates the sum of two numbers and returns
the result.
<?php function add($a, $b) { return $a + $b; // Returning the sum } $result = add(5, 7); echo "Sum: $result"; // Outputs "Sum: 12" ?>
Explanation:
- The function
add($a, $b)
calculates the sum andreturns
it. - The returned value is stored in
$result
. - It is then printed using
echo
.
📝 Example 2: Returning a String Value
A function can return text values too.
<?php function greet($name) { return "Hello, $name!"; } $message = greet("Alice"); echo $message; // Outputs "Hello, Alice!" ?>
Explanation:
- The function returns a greeting message.
- The returned value is stored in
$message
and displayed.
📝 Example 3: Returning Multiple Values Using an Array
PHP functions can return multiple values by using arrays
.
<?php function getUser() { return array("Alice", 25, "Developer"); } $user = getUser(); echo "Name: " . $user[0] . ", Age: " . $user[1] . ", Job: " . $user[2]; ?>
Explanation:
- The function returns an
array
with three values. - The values are accessed using array indexes (
[0]
,[1]
,[2]
).
🎯 Key Takeaways
- Use
return
to send values from a function. - You can return numbers, strings, and even arrays.
- Stored return values can be used in calculations, conditions, or other functions.
📝 Practice Time!
Modify these examples and try different values to understand how return values
work in PHP!