Introduction
Return values allow PHP functions to send calculated results back to the code that calls them. PHP functions can return numbers, strings, and arrays. By returning an array, you can also handle multiple results from a single function. In this tutorial, you will learn how to return and reuse values through simple practical examples. Return Values and Returning Multiple Results in PHP Solved Practice Questions to help you to understand the concepts.
Question 1: Return a Simple Value from a Function
Return values allow PHP functions to send calculated results back to the code that calls them. PHP functions can return numbers, strings, and arrays. By returning an array, you can also handle multiple results from a single function. In this tutorial, you will learn how to return and reuse values through simple practical examples.
Problem Statement:
Create a function named getInstituteName() that returns the name of an institute. Store the returned value in a variable and display it.
PHP Solution:
<?php
function getInstituteName() {
return "VSIT Coding Institute";
}
$institute = getInstituteName();
echo "Institute Name: " . $institute;
?>
Sample Output:
Institute Name: VSIT Coding Institute
Explanation:
- The function returns a string using the
returnstatement. - The function call sends the returned value to
$institute. - The
echostatement displays the stored value.
Concepts Covered:
- Return statement
- Returning string values
- Storing returned values
Question 2: Return the Sum of Two Numbers
Problem Statement:
Create a function named calculateSum() that accepts two numbers and returns their sum.
PHP Solution:
<?php
function calculateSum($num1, $num2) {
$total = $num1 + $num2;
return $total;
}
$result = calculateSum(1500, 2500);
echo "Total: " . $result;
?>
Sample Output:
Total: 4000
Explanation:
- The function receives two numbers.
- It calculates their sum and stores the result in
$total. - The
returnstatement sends the result back to the calling code. - The returned value is stored in
$result.
Concepts Covered:
- Returning calculated values
- Function parameters
- Using returned results
Question 3: Return the Average of Student Marks
Problem Statement:
Create a function named calculateAverage() that accepts three subject marks and returns their average.
PHP Solution:
<?php
function calculateAverage($maths, $science, $english) {
$total = $maths + $science + $english;
return $total / 3;
}
$average = calculateAverage(85, 90, 80);
echo "Average Marks: " . $average;
?>
Sample Output:
Average Marks: 85
Explanation:
- The function accepts marks for three subjects.
- It calculates the total marks.
- The total is divided by three to calculate the average.
- The average is returned to the calling code.
Concepts Covered:
- Returning average values
- Mathematical calculations
- Multiple function parameters
Question 4: Return a Boolean Value
Problem Statement:
Create a function named isEligibleToVote() that accepts a person’s age and returns true if the age is 18 or above. Otherwise, return false.
PHP Solution:
<?php
function isEligibleToVote($age) {
if ($age >= 18) {
return true;
}
return false;
}
$result = isEligibleToVote(20);
if ($result) {
echo "Eligible to Vote";
} else {
echo "Not Eligible to Vote";
}
?>
Sample Output:
Eligible to Vote
Explanation:
- The function checks whether the age is 18 or above.
- It returns
truewhen the condition is satisfied. - Otherwise, it returns
false. - The returned Boolean value is used in an
if-elsestatement.
Concepts Covered:
- Returning Boolean values
- Conditional statements
- Using returned values in conditions
Question 5: Return a Value Based on a Condition
Problem Statement:
Create a function named getResult() that accepts student marks and returns Pass if marks are 40 or above. Otherwise, return Fail.
PHP Solution:
<?php
function getResult($marks) {
if ($marks >= 40) {
return "Pass";
}
return "Fail";
}
$result = getResult(75);
echo "Student Result: " . $result;
?>
Sample Output:
Student Result: Pass
Explanation:
- The function receives student marks.
- It checks whether the marks are at least 40.
- Depending on the condition, it returns either
PassorFail. - The returned string is stored in
$result.
Concepts Covered:
- Conditional return statements
- Returning strings
- Function results
Question 6: Return Multiple Values Using an Array
Problem Statement:
Create a function named getEmployeeDetails() that returns an employee’s name, department, and salary as an associative array.
PHP Solution:
<?php
function getEmployeeDetails() {
return [
"name" => "Amit",
"department" => "IT",
"salary" => 35000
];
}
$employee = getEmployeeDetails();
echo "Name: " . $employee["name"] . "\n";
echo "Department: " . $employee["department"] . "\n";
echo "Salary: " . $employee["salary"];
?>
Sample Output:
Name: Amit
Department: IT
Salary: 35000
Explanation:
- A PHP function returns one value directly.
- That value can be an array containing multiple pieces of information.
- The associative array stores employee details using named keys.
- Each value can be accessed using its key.
Concepts Covered:
- Returning arrays
- Associative arrays
- Returning multiple results
- Accessing array values
Question 7: Return Multiple Calculations from a Function
Problem Statement:
Create a function named calculateNumbers() that accepts two numbers and returns their addition, subtraction, multiplication, and division results in an associative array.
PHP Solution:
<?php
function calculateNumbers($a, $b) {
return [
"addition" => $a + $b,
"subtraction" => $a - $b,
"multiplication" => $a * $b,
"division" => $a / $b
];
}
$results = calculateNumbers(20, 5);
echo "Addition: " . $results["addition"] . "\n";
echo "Subtraction: " . $results["subtraction"] . "\n";
echo "Multiplication: " . $results["multiplication"] . "\n";
echo "Division: " . $results["division"];
?>
Sample Output:
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4
Explanation:
- The function performs four mathematical calculations.
- Each result is stored under a separate array key.
- The complete array is returned.
- Individual results are accessed using their keys.
Concepts Covered:
- Returning multiple calculations
- Associative arrays
- Accessing returned results
Question 8: Return Multiple Values Using list() Destructuring
Problem Statement:
Create a function named getStudentMarks() that returns three subject marks in an indexed array. Use list() to store each returned value in a separate variable.
PHP Solution:
<?php
function getStudentMarks() {
return [85, 90, 78];
}
list($maths, $science, $english) = getStudentMarks();
echo "Maths: " . $maths . "\n";
echo "Science: " . $science . "\n";
echo "English: " . $english;
?>
Sample Output:
Maths: 85
Science: 90
English: 78
Explanation:
- The function returns an indexed array containing three marks.
list()assigns each array value to a separate variable.- The first value goes into
$maths. - The second value goes into
$science. - The third value goes into
$english.
Concepts Covered:
- Returning indexed arrays
list()construct- Array destructuring
Question 9: Return an Array of Filtered Results
Problem Statement:
Create a function named getPassedStudents() that accepts an array of student marks and returns only the marks of students who scored 40 or above.
PHP Solution:
<?php
function getPassedStudents($marks) {
$passed = [];
foreach ($marks as $mark) {
if ($mark >= 40) {
$passed[] = $mark;
}
}
return $passed;
}
$studentMarks = [85, 32, 67, 25, 90, 45];
$passedMarks = getPassedStudents($studentMarks);
echo "Passed Students' Marks:\n";
foreach ($passedMarks as $mark) {
echo $mark . "\n";
}
?>
Sample Output:
Passed Students' Marks:
85
67
90
45
Explanation:
- The function receives an array of marks.
- The
foreachloop checks each mark. - Marks of 40 or above are added to the
$passedarray. - The function returns the completed array.
- Another loop displays the returned values.
Concepts Covered:
- Returning filtered arrays
foreachloop- Conditional statements
- Array elements
Question 10: Return an Employee Salary Summary
Problem Statement:
Create a function named calculateSalarySummary() that accepts an employee’s basic salary, allowance, and deduction. Return the basic salary, total earnings, total deductions, and net salary in an associative array.
PHP Solution:
<?php
function calculateSalarySummary($basic, $allowance, $deduction) {
$totalEarnings = $basic + $allowance;
$netSalary = $totalEarnings - $deduction;
return [
"basic_salary" => $basic,
"total_earnings" => $totalEarnings,
"total_deductions" => $deduction,
"net_salary" => $netSalary
];
}
$salary = calculateSalarySummary(30000, 5000, 3000);
echo "Basic Salary: " . $salary["basic_salary"] . "\n";
echo "Total Earnings: " . $salary["total_earnings"] . "\n";
echo "Total Deductions: " . $salary["total_deductions"] . "\n";
echo "Net Salary: " . $salary["net_salary"];
?>
Sample Output:
Basic Salary: 30000
Total Earnings: 35000
Total Deductions: 3000
Net Salary: 32000
Explanation:
- The function receives basic salary, allowance, and deduction.
- Total earnings are calculated by adding basic salary and allowance.
- Net salary is calculated after subtracting deductions.
- All four results are returned in an associative array.
- The returned values are displayed using their array keys.
Concepts Covered:
- Returning multiple results
- Salary calculations
- Associative arrays
- Reusing returned data
Key Takeaways
- The
returnstatement sends a value back from a function. - A function can return numbers, strings, Boolean values, and arrays.
- Returned values can be stored in variables.
- A function can return an associative array containing multiple results.
- Indexed arrays can also be used to return multiple values.
list()can assign returned array values to separate variables.- A returned array can be used for calculations, reports, and data processing.
- The
returnstatement immediately ends the function’s execution.
Frequently Asked Questions (FAQs)
1. What is a return value in PHP?
A return value is the result sent back by a function using the return statement.
2. How do you return a value from a PHP function?
Use the return statement followed by the value you want to send back.
function getNumber() {
return 100;
}
3. Can a PHP function return multiple values?
A PHP function returns one value directly. However, you can return an array containing multiple values and access each result separately.
4. How can you return multiple values using an array?
Create an indexed or associative array inside the function and return it using the return statement.
5. Can a PHP function return an array?
Yes. PHP functions can return indexed arrays, associative arrays, and multidimensional arrays.
6. What happens when PHP executes a return statement?
The function immediately stops executing and sends the specified value back to the calling code.
7. What happens if a PHP function has no return statement?
The function returns null by default if no value is returned.
8. Can we store a function’s return value in a variable?
Yes. You can store the returned value in a variable and use it later.
$result = calculateSum(10, 20);
9. What is the difference between echo and return in PHP?
echo displays information on the screen, while return sends a value back to the code that called the function.
10. What is the use of list() when returning multiple results?
list() assigns values from an indexed array to separate variables, making it easier to work with multiple returned results.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
