
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Returning two values from a function in PHP
Two variables can’t be explicitly returned, they can be put in a list/array data structure and returned.
Example
function factors( $n ) { // An empty array is declared $fact = array(); // Loop through it for ( $i = 1; $i < $n; $i++) { // Check if i is the factor of // n, push into array if( $n % $i == 0 ) array_push( $fact, $i ); } // Return array return $fact; } // Declare a variable and initialize it $num = 12; // Function call $nFactors = factors($num); // Display the result echo 'Factors of ' . $num . ' are: <br>'; foreach( $nFactors as $x ) { echo $x . "<br>"; }
Output
This will produce the following output −
Factors of 12 are: 1 2 3 4 6
- Related Articles
- Returning multiple values from a C++ function
- PHP Returning values
- Returning multiple values from a function using Tuple and Pair in C++
- Returning values from a constructor in JavaScript?
- Function returning another function in JavaScript
- Returning Multiple Values in Python?
- Returning Value from a Subroutine in Perl
- Returning an Array from a Method in Java
- How can we fetch all the data from MySQL table by using mysql_fetch_array() function, returning an array with the numeric index, in PHP script?
- Returning array values that are not odd in JavaScript
- MongoDB query to limit the returning values of a field?
- Declare a C/C++ function returning pointer to array of integer function pointers
- Returning lengthy words from a string using JavaScript
- How to apply a function simultaneously against two values of the array from left-to-right?
- How to apply a function simultaneously against two values of the array from right-to-left?

Advertisements