Lesson 28 of 50 – PHP Return Values
56%

PHP Return Values

In PHP, the return statement sends a value from a function back to the code that called it. Returned values can be stored in variables, displayed, or used in calculations and other functions.

1. Understanding the Return Statement

The return statement sends a value back to the calling code and ends the current function.

<?php
function getNumber() {
    return 100;
}

$result = getNumber();

echo $result;
?>
Output:
100

The function returns 100, and the returned value is stored in the $result variable.

2. Returning the Result of a Calculation

A function can calculate a result and return it instead of displaying it directly.

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(10, 20);
?>
Output:
30

Another example:

<?php
function multiply($a, $b) {
    return $a * $b;
}

$result = multiply(5, 4);

echo "Multiplication: " . $result;
?>
Output:
Multiplication: 20
3. Difference Between echo and return

echo displays output, while return sends a value back to the caller.

Example using echo:

<?php
function showSum($a, $b) {
    echo $a + $b;
}

showSum(10, 5);
?>
Output:
15

Example using return:

<?php
function calculateSum($a, $b) {
    return $a + $b;
}

$result = calculateSum(10, 5);

echo "Result: " . $result;
?>
Output:
Result: 15

Use return when you need to reuse a function's result in other parts of your program.

4. Returning a String

A function can return text, such as a name, message, course title, or status.

<?php
function getWelcomeMessage($name) {
    return "Welcome to PHP, " . $name . "!";
}

$message = getWelcomeMessage("Rahul");

echo $message;
?>
Output:
Welcome to PHP, Rahul!

Example: Return a course name

<?php
function getCourse() {
    return "Web Development";
}

echo "Course: " . getCourse();
?>
Output:
Course: Web Development
5. Returning a Boolean Value

A function can return true or false to indicate whether a condition is satisfied.

<?php
function isAdult($age) {
    return $age >= 18;
}

var_dump(isAdult(20));
var_dump(isAdult(15));
?>
Output:
bool(true)
bool(false)

Example: Check an even number

<?php
function isEven($number) {
    return $number % 2 === 0;
}

if (isEven(8)) {
    echo "Even number";
} else {
    echo "Odd number";
}
?>
Output:
Even number
6. Returning an Array

A function can return an entire array containing multiple values.

<?php
function getColors() {
    return ["Red", "Green", "Blue"];
}

$colors = getColors();

print_r($colors);
?>
Output:
Array
(
    [0] => Red
    [1] => Green
    [2] => Blue
)

Accessing returned array values:

<?php
function getStudent() {
    return [
        "name" => "Rahul",
        "course" => "PHP",
        "city" => "Patna"
    ];
}

$student = getStudent();

echo $student["name"] . "<br>";
echo $student["course"] . "<br>";
echo $student["city"];
?>
Output:
Rahul
PHP
Patna
7. Returning Early from a Function

A return statement immediately ends the current function. It can be used to handle conditions before continuing with the remaining code.

<?php
function divide($a, $b) {
    if ($b == 0) {
        return "Cannot divide by zero";
    }

    return $a / $b;
}

echo divide(10, 2);
echo "<br>";
echo divide(10, 0);
?>
Output:
5
Cannot divide by zero

When the divisor is zero, the function returns an error message immediately. The division statement is not executed in that case.

Example: Check a score

<?php
function getResult($marks) {
    if ($marks < 0 || $marks > 100) {
        return "Invalid marks";
    }

    if ($marks >= 40) {
        return "Pass";
    }

    return "Fail";
}

echo getResult(75);
?>
Output:
Pass
8. Using One Function's Return in Another Function

A returned value can be passed directly to another function or used in a larger expression.

<?php
function square($number) {
    return $number * $number;
}

function addFive($number) {
    return $number + 5;
}

echo addFive(square(4));
?>
Output:
21

First, square(4) returns 16. Then addFive(16) returns 21.

Example: Calculate a discounted price

<?php
function calculateDiscount($price, $discountPercent) {
    return $price * $discountPercent / 100;
}

function finalPrice($price, $discountPercent) {
    $discount = calculateDiscount($price, $discountPercent);

    return $price - $discount;
}

echo finalPrice(1000, 10);
?>
Output:
900
9. Practical Example: Student Result System

This example uses return values to calculate total marks, percentage, and the final result.

<?php
function calculateTotal($marks) {
    return array_sum($marks);
}

function calculatePercentage($total, $maximumMarks) {
    if ($maximumMarks <= 0) {
        return 0;
    }

    return ($total / $maximumMarks) * 100;
}

function getResult($percentage) {
    return $percentage >= 40 ? "Pass" : "Fail";
}

$studentName = "Rahul";
$marks = [80, 75, 85];

$total = calculateTotal($marks);
$percentage = calculatePercentage($total, 300);
$result = getResult($percentage);

echo "Student: " . $studentName . "<br>";
echo "Total Marks: " . $total . " / 300<br>";
echo "Percentage: " . number_format($percentage, 2) . "%<br>";
echo "Result: " . $result;
?>
Output:
Student: Rahul
Total Marks: 240 / 300
Percentage: 80.00%
Result: Pass

Each function performs one task and returns a result that another part of the program can reuse.

Practice Assignments
  1. Create a function that returns the sum of two numbers.
  2. Create a function that returns the square of a number.
  3. Create a function that returns a welcome message.
  4. Create a function that returns true for an even number.
  5. Create a function that returns an array of five fruits.
  6. Create a function that returns the largest of three numbers.
  7. Create a function that returns the area of a rectangle.
  8. Create a function that returns the final price after a discount.
  9. Create a student result system using total, percentage, and result functions.

🧠 Quick Quiz

1. Which statement sends a value back from a function?




2. What happens when a function executes a return statement?




3. Which PHP function displays an array's structure and values?